<?php

namespace App\Http\Controllers;

use App\ABFL\Services\Services;
use App\AccountAggregator;
use App\AdminLoginLogs;
use App\Avanse\Services\AvanseServices;
use App\CallLogs;
use App\CampaignsJobProvider;
use App\Events\V1\EventPayTMUpdate;
use App\Http\Controllers\Admin\AccountingController;
use App\Http\Controllers\Admin\RepaymentController;
use App\KarzaAPI;
use App\Centers;
use App\CityModel;
use App\Comments;
use App\ConsumerApplicationElement;
use App\DigitalSignDetails;
use App\Events\V1\EventAccountAggregatorWebhook;
use App\Events\V1\EventPirimidWebhook;
use App\Events\V1\EventDigioWebhook;
use App\Events\V1\EventAutoDecision;
use App\Events\V1\EventHypothecation;
use App\FCMNotification;
use App\finBoxIntegration;
use App\GCMRegistraion;
use App\Http\Controllers\Admin\UtkarshController;
use App\Http\Controllers\TestingController;
use App\Http\Controllers\Admin\ConsumerApplicationController;
use App\Http\Controllers\Admin\ConsumerDocument;
use App\Http\Controllers\Service\ServiceController;
use App\Http\Controllers\Admin\EMICalculation;
use App\JobProvider;
use App\KMGP2P;
use App\Leads;
use App\Lenders;
use App\Lib\Common\Utility;
use App\LoanHypothecation\LoanHypothecation;
use App\LoanHypothecation\DigioHypothecation;
use App\LoanHypothecationModel;
use App\LoanManagement;
use App\MandatoryDocumentListLogs;
use App\Merchant;
use App\MerchantLocation;
use App\MerchantOffers;
use App\Method\Homeville\Payload\Payload;
use App\OnfidoIntegration;
use App\OnlinePayment;
use App\OtpManager;
use App\PaymentEmi;
use App\PaymentTransaction;
use App\ProFormaInvoice;
use App\ProjectLead\ProjectLeads;
use App\PWAApplicationForm;
use App\QueueLog;
use App\Shortio;
use App\Slack;
use App\StatusLogs;
use App\TelecomDetails;
use App\Templates;
use App\Trello;
use App\User;
use App\UserTypes;
use App\Utkarsh\Utkarsh;
use App\UtkarshKYCData;
use App\WebHookLog;
use Carbon\Carbon;
use Hashids\Hashids;
use Illuminate\Http\Request;
use App\ConsumerApplication;
use App\ConsumerApplicationAdditional;
use App\ConsumerApplicationFiles;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Lang;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\Rules\In;
use App\Events\V1\EventPostFormCompleted;
use App\Logging\CloudWatchLoggerFactory;
use App\DigioVKYC;
use App\UserGeolocation;
use App\ConsentLog;
use Illuminate\Support\Facades\App;
use App\KYCDetails;
use App\Vendor;
use App\Console\Commands\VendorWebhook;
use App\Http\Controllers\WebhookController;
use App\Http\Controllers\Admin\autoBRE;
use App\Imports\TestImport;
use App\Http\Controllers\Grade\GradeController;
use App\UtilityValidation;
use App\NameMatchService;

class ApiController extends Controller
{
    public $current_status = 'form completed';

    /*public function generateOtpEsign(Request $request)
    {
        try {
            $inputs = $request->all();

            $validator = $this->validateMobileNumber($inputs);
            if($validator->fails()) {
                return Utility::sendValidationFailed($validator->errors());
            }
            $mobile_number = Arr::get($inputs,'mobile_number');
            if (strlen($mobile_number) == 12 && substr($mobile_number, 0, 2) == "91") {
                $mobile_number = substr($mobile_number, 2, 10);
            } else if (strlen($mobile_number) != 10) {
                return Utility::sendFailed([ 'mobile_number' => [Lang::get('message.invalid_input')]]
                    ,null, null,
                    Lang::get('message.def_err_msg'));
            }
            $otp = rand('100000', '999999');
            $otpObj = OtpManager::addEntry($otp, $mobile_number, $inputs);
            return Utility::sendSuccess([],Lang::get("message.otp_success"));
        } catch(\Exception $e) {
            report($e);
            return Utility::sendFailed($e->getMessage(),null, 500, Lang::get('auth.general_code'));
        }
    }*/
    public $isSystemByPass = false;

    public function generateOtpEsign(Request $request)
    {

        $otp = rand('100000', '999999');
        $mobile_number = $request->input('mobile_number');

        if (strlen($mobile_number) == 12 && substr($mobile_number, 0, 2) == "91") {
            $mobile_number = substr($mobile_number, 2, 10);
        }

        $message = "Your Credit Fair verification code is ".$otp."<br/>Best Regards,<br/>Team Credit Fair";
        $entity = ['templateid' => '1307161519272825845', 'entityid' => Templates::$entityid];

        OtpManager::where('mobile_number', (string)$mobile_number)->delete();
        $otp_manager = new \App\OtpManager();
        $otp_manager->otp = $otp;
        $otp_manager->mobile_number = $mobile_number;
        $otp_manager->save();

        $this->sendOTPOnEmail($request, $otp, $mobile_number);

        $mobile_number = '91' . $mobile_number;
        send_sms($mobile_number, ['message' => $message, 'OTP' => true, 'templateDetails' => $entity]);

        $data['status'] = 'success';
        $data['message'] = 'OTP request sent';
        return response()->json($data);
    }
    public function getReferenceDetails(Request $request){
        // $mobile_number = "7021378383";
        $mobile_number = $request->get('reference_mobile');
        $referenceDetail = (new KarzaAPI())->getReferenceDetailsFromNumber($mobile_number);
        if($referenceDetail){
            if(isset($referenceDetail['statusCode']) && $referenceDetail['statusCode'] == 101){
                return ['status'=>'OK',
                    'message' => $referenceDetail['result']['vpaDetails'][0]['nameAtBank']
                ];
            }else{
                return ['status'=>'FAIL',
                    'message' => 'No data found'
                ];
            }
        }
        return ['status'=>'FAIL',
        'message' =>'No data fount'
    ];
    }

    public function sendOTPOnEmail(Request $request, $otp, $mobile_number,$purpose = ""){
        if($purpose == "LOGIN"){
            $email = $request->get('email');
            if(isset($email) && $email != ""){
                $message = "<br/>By validating OTP ".$otp." I agree to Credit Fair's terms and conditions provided here - <a href=".asset("https://bit.ly/2QRVgjd").">https://bit.ly/2QRVgjd</a>, for the loan application and have no objection to them conducting a credit check or contacting me. You can view your loan application status through our consumer application by logging through the link <a href=".asset("https://bit.ly/3pkSXS6").">https://bit.ly/3pkSXS6</a>. Team Credit Fair";
                $email = explode(',', $email);
                Mail::send('emails.reminders.basic_reminder',
                    ['body'=> $message]
                    , function ($message) use ($email) {
                        $message->to($email)->subject('OTP for login with Credit Fair');
                    });
            }
        }else{

            if($request->has('application_id')) {
                if($request->has('applicant') && $request->get('applicant') == 1){
                    $data = ConsumerApplication::where('id', $request->get('application_id'))->where('mobile_number', $mobile_number)->first(['email', 'name']);
                }else{
                    $data = ConsumerApplication::where('id', $request->get('application_id'))->where('co_applicant_mobile_number', $mobile_number)->first(['co_applicant_email as email', 'co_applicant_name as name']);
                }
            }else if ($request->has('merchant_id')){
                $data = Merchant::where('id', $request->get('merchant_id'))->first(['email', 'merchant_name as name']);
            }

            $merchant_id_check = $request->has('merchant_id') ? $request->get('merchant_id') : ($data->merchant_id ?? 0);
            if(isset($data->email) && $data->email  && $merchant_id_check!= _env("Finsall_id")){
                $message = "Dear ".$data->name.",<br/>Your OTP for E-Signing Agreement with Credit Fair is  ".$otp.".";
                $email = explode(',', $data->email);
                Mail::send('emails.reminders.basic_reminder',
                    ['body'=> $message]
                    , function ($message) use ($email) {
                        $message->to($email)->subject('OTP for E-Signing Agreement with Credit Fair');
                    });
            }
        }
    }

    public function generateOtp(Request $request)
    {
        $otp           = rand('100000', '999999');
        $mobile_number = $request->input('mobile_number');
        $email = $request->input('email');
        $message = "Your Credit Fair verification code is ".$otp."<br/>Best Regards,<br/>Team Credit Fair";
        $entity = ['templateid' => '1307161519272825845', 'entityid' => Templates::$entityid];

        if($request->has('page') && $request->get('page') == 'lp-page'){
            if (strlen($mobile_number) == 12 && substr($mobile_number, 0, 2) == "91") {
                $mobile_number = substr($mobile_number, 2, 10);
            }

            OtpManager::where('mobile_number', (string)$mobile_number)->delete();
            $otp_manager                = new \App\OtpManager();
            $otp_manager->otp           = $otp;
            $otp_manager->mobile_number = $mobile_number;
            $otp_manager->save();

            $mobile_number = '91' . $mobile_number;
            send_sms($mobile_number, ['message'=>$message, 'OTP' => true, 'templateDetails' => $entity]);
            $data['status']  = 'success';
            $data['message'] = 'OTP request sent';
            $data['request_id'] = "";
            return response()->json($data);
        }

        if ($request->server->has('HTTP_REFERER') && (strpos($request->server->get('HTTP_REFERER'), '/application/login') === false)) {
            if ($errorCode = $this->checkEligibility($request)) {
                $data['error']['eligibility'] = $errorCode;
                return response()->json($data, 200);
            }
            if (($request->has('isResend') && $request->get('isResend') == 0) || !$request->has('isResend')) {
                $telecom = new TelecomDetails();
                $response = $telecom->generateOtp($mobile_number);
                if ($response != false) {
                    $data['request_id'] = $response['request_id'];
                    //$message = "By sharing otp you agree to Credit Fair's terms and conditions (https://bit.ly/2QRVgjd) for the loan application and have no objection to them conducting a credit check";
                    $message = "By sharing OTP  you agree to Credit Fair’s terms and conditions provided here - (https://bit.ly/2QRVgjd) for the loan application and have no objection to them conducting a credit check or being contacted by them.<br/>You can view your loan application status through our consumer application by login through below link https://bit.ly/3pkSXS6";
                    $mobile_number = '91' . $mobile_number;
                    send_sms($mobile_number, ['message'=>$message, 'OTP' => true]);
                    $data['status'] = 'success';
                    $data['message'] = 'OTP request sent';
                    return response()->json($data);
                }
            }
            //$message = "By validating OTP $otp I agree to Credit Fair's terms and conditions https://bit.ly/2QRVgjd for the loan application and have no objection to them conducting a credit check.<br/>Best Regards,<br/>Team Credit Fair";
            //$message = "By validating OTP ".$otp." I agree to Credit Fair's terms and conditions (https://bit.ly/2QRVgjd), for the loan application and have no objection to them conducting a credit check & sending notifications on Whatsapp";
            // $message = "By validating OTP $otp I agree to Credit Fair's terms and conditions provided here - https://bit.ly/2QRVgjd, for the loan application and have no objection to them conducting a credit check or contacting me.<br/>You can view your loan application status through our consumer application by login through below link https://bit.ly/3pkSXS6<br>Best Regards,<br/>Team Credit Fair";
            $tnC_link = "https://lnk.creditfair.in/hFVR";
            $app_link = "https://lnk.creditfair.in/Wgmx";
            // $message = "By validating OTP ".$otp." I agree to Credit Fair's terms and conditions provided here - https://bit.ly/2QRVgjd, for the loan application and have no objection to them conducting a credit check or contacting me. You can view your loan application status through our consumer application by logging through the link https://bit.ly/3pkSXS6. Team Credit Fair";
            $message = "By validating OTP ".$otp." I agree to Credit Fair's terms and conditions provided here - ".$tnC_link.", for the loan application and have no objection to them conducting a credit check or contacting me. You can view your loan application status through our consumer application by logging through the link ".$app_link." . Team Credit Fair";
            if($email != "") {
                $request = new Request();
                $request->merge(['applicant' => 1]);
                $request->merge(['email' => $email]);

                // $otp = rand('100000', '999999');
                $purpose = "LOGIN";
                $this->sendOTPOnEmail($request,$otp,$mobile_number,$purpose);
            }
            $entity = ['templateid' => '1307173277417496907', 'entityid' => Templates::$entityid];
        }else{
            $isExist = User::where('mobile_number',$mobile_number)->whereNull('deleted_at')->first(['id']);
            if(!isset($isExist->id)){
                $consumer = ConsumerApplication::where('mobile_number',$mobile_number)->wherenull('is_deleted')->first();
                if(isset($consumer->id)){
                    $usernew = new User();
                    $usernew->name = $consumer->name;
                    $usernew->username = $consumer->name;
                    $usernew->email = $consumer->email;
                    $usernew->mobile_number = $consumer->mobile_number;
                    $usernew->user_type = 1;
                    $usernew->save();
                }else {
                    return response()->json(['status' => 'fail', 'message' => 'Invalid mobile number']);
                }
            }
        }

        if (strlen($mobile_number) == 12 && substr($mobile_number, 0, 2) == "91") {
            $mobile_number = substr($mobile_number, 2, 10);
        }

        OtpManager::where('mobile_number', (string)$mobile_number)->delete();
        $otp_manager                = new \App\OtpManager();
        $otp_manager->otp           = $otp;
        $otp_manager->mobile_number = $mobile_number;
        $otp_manager->save();

        $mobile_number = '91' . $mobile_number;
        send_sms($mobile_number, ['message'=>$message, 'OTP' => true, 'templateDetails' => $entity]);
        if($request->get('isEmail')){

            $user = User::where('mobile_number',$request->input('mobile_number'))->where('user_type', '>=', 5)->whereNotNull('email')->whereNull('deleted_at')->first(['id','email','name']);

            if(isset($user->email) && $user->email){
                $message = "Dear ".$user->name.",<br/>Your OTP for login with Credit Fair is  ".$otp.".";
                $email = $user->email;
                Mail::send('emails.reminders.basic_reminder',
                    ['body'=> $message]
                    , function ($message) use ($email) {
                        $message->to($email)->subject('OTP for Login with Credit Fair');
                    });
            }
        }

        $data['status']  = 'success';
        $data['message'] = 'OTP request sent';
        $data['request_id'] = "";
        return response()->json($data);
    }

    public function verifyesignOtpMerchant(Request $request)
    {

        $mobile_number = $request->input('mobile_number');

        if (strlen($mobile_number) == 12 && substr($mobile_number, 0, 2) == "91") {
            $mobile_number = substr($mobile_number, 2, 10);
        }

        if (\App\OtpManager::where('mobile_number', (string)$mobile_number)->where('otp', $request->input('otp'))->first()) {

            \App\OtpManager::where('mobile_number', (string)$mobile_number)->delete();

            $digital_sign = new DigitalSignDetails();
            $digital_sign->application_id = $request->input('merchant_id');
            $digital_sign->applicant = 1;
            $digital_sign->load_time = date('Y-m-d H:i:s',strtotime($request->input('startdatetime')));
            $digital_sign->click_time = date('Y-m-d H:i:s',strtotime($request->input('clickdatetime')));
            $digital_sign->isaddress =  $this->get_client_ip();
            $digital_sign->isagreementsigned =  0;
            $digital_sign->language = 'ENGLISH';
            $digital_sign->merchant_esign_image = $this->getUploadMerchantMedia($request->input('img'), $request->input('merchant_id'));
            $digital_sign->type = "merchant";
            $digital_sign->client = json_encode($request->get('getClientInfo'));
            $digital_sign->save();

            $appObj = new \stdClass();
            $appObj->id = $request->input('merchant_id');
            (new ConsumerApplicationController())->saveUserGeolocation($appObj, ['applicant_type' => 1, 'id_type' => 'merchant_id','service' => 'esign', 'longitude' => $request->input('a_lg_d'), 'latitude' => $request->input('a_lt_d')]);

            $data['status']  = 'success';
            $data['message'] = 'OTP successfully verified';
            $hashids = new Hashids('Creditfair by CS', 20);
            $hashid = $hashids->encode($request->input('merchant_id'));
            $data['redirect'] = asset("esignupdatemerchant/id/".$hashid);

            return response()->json($data);
        } else {
            $data['status']  = 'failure';
            $data['message'] = 'OTP verification failed';
            return response()->json($data);
        }
    }

    public function getUploadMerchantMedia($data, $id){
        if(isset(explode(',',$data)[1])) {
            return (new ConsumerDocument(new Request()))->uploadMerchantToS3('merchant_cam_image', $id, base64_decode(explode(',',$data)[1]));
        }
        return '';
    }

    public function getUploadCustomerMedia($data, $id, $name, $applicant_type = 1){
        if(isset(explode(',',$data)[1])) {
            return (new ConsumerDocument(new Request()))->uploadCustomerToS3($name, $id, base64_decode(explode(',',$data)[1]), $applicant_type);
        }
        return '';
    }


    public function verifyesignOtp(Request $request)
    {

        $mobile_number = $request->input('mobile_number');
        $merchant_id = $request->input('merchant_id');

        if (strlen($mobile_number) == 12 && substr($mobile_number, 0, 2) == "91") {
            $mobile_number = substr($mobile_number, 2, 10);
        }

        $remove_esign_otp = 0;
        if ($merchant_id){
            $merchant = Merchant::where('id', $merchant_id)->first(['remove_esign_otp']);
            if (isset($merchant->remove_esign_otp) && $merchant->remove_esign_otp){
                $remove_esign_otp = 1;
            }
        }

        if (\App\OtpManager::where('mobile_number', (string)$mobile_number)->where('otp', $request->input('otp'))->first() || ($remove_esign_otp && $request->input('skipOtp'))) {
        //if (\App\OtpManager::where('mobile_number', $mobile_number)->where('otp', $request->input('otp'))->first() || ($merchant_id == 31 && $request->input('skipOtp'))) {

            if(!$request->input('skipOtp') || ($request->input('skipOtp') == false || $request->input('skipOtp') == 'false')){
                \App\OtpManager::where('mobile_number', (string)$mobile_number)->delete();
            }

            $isExist = DigitalSignDetails::where('application_id', $request->input('application_id'))->where('applicant', $request->input('applicant'))->first(['id']);
            if (isset($isExist->id)){
                $application = ConsumerApplication::where('id', $request->input('application_id'))->first(['name','co_applicant_name']);
                $customer_name = $request->input('applicant') == 1 ? $application->name : $application->co_applicant_name;
                $data['status']  = 'failure';
                $data['message'] = 'Agreement already signed for '.$customer_name.'. Please refresh the page.';
                return response()->json($data);
            }

            $digital_sign = new DigitalSignDetails();
            $digital_sign->application_id = $request->input('application_id');
            $digital_sign->applicant = $request->input('applicant');
            $digital_sign->load_time = date('Y-m-d H:i:s',strtotime($request->input('startdatetime')));
            $digital_sign->click_time = date('Y-m-d H:i:s',strtotime($request->input('clickdatetime')));
            $digital_sign->isaddress =  $this->get_client_ip();
            $digital_sign->isagreementsigned =  0;
            $digital_sign->language = $request->input('language');
            $digital_sign->client = json_encode($request->get('getClientInfo'));
            if($request->input('applicant') == 2){
                $media_name_file = 'co_applicant_cam_image';
            }else{
                $media_name_file = 'customer_cam_image';
            }
            $digital_sign->merchant_esign_image = $this->getUploadCustomerMedia($request->input('img'), $request->input('application_id'), $media_name_file);
            $digital_sign->type = "consumer";
            $digital_sign->save();
            $data['status']  = 'success';
            $data['message'] = 'OTP successfully verified';
            $hashids = new Hashids('Creditfair by CS', 20);
            $hashid = $hashids->encode($request->input('application_id'));

            $hashidApplicant = $hashids->encode($request->input('applicant'));
            $data['redirect'] = asset("esignupdate/id/".$hashid.'?app='.$hashidApplicant);

            $appObj = new \stdClass();
            $appObj->id = $request->input('application_id');

            $consumerApplication = ConsumerApplication::where('id',$request->input('application_id'))->first(['id', 'applicant_id', 'name','co_applicant_id', 'user_id', 'lender_id', 'mobile_number', 'co_applicant_name', 'co_applicant_mobile_number']);

            if($request->input('skipOtp') == 'false'){
            //if($merchant_id == 31 && $request->input('skipOtp') == 'false'){
                User::where('mobile_number', $mobile_number)->update(['user_verified' => 1]);
            }

            $applicant_id = $consumerApplication ? ($request->input('applicant') == 1 ? $consumerApplication->applicant_id : $consumerApplication->co_applicant_id) : 0;

            $consumerApplicationController = (new ConsumerApplicationController());

            $consumerApplicationController->saveUserGeolocation($appObj, ['applicant_id' => $applicant_id,'applicant_type' => $request->input('applicant'),'id_type' => 'application_id','service' => 'esign', 'longitude' => $request->input('a_lg_d'), 'latitude' => $request->input('a_lt_d')]);
            $consumerApplicationController->saveConsent($consumerApplication, $request->input('applicant'), ['longitude' => $request->input('a_lg_d'), 'latitude' => $request->input('a_lt_d')]);


            return response()->json($data);
        } else {
            $data['status']  = 'failure';
            $data['message'] = 'OTP verification failed';
            return response()->json($data);
        }
    }

    public function get_client_ip() {
        try {
            $ipaddress = '';
            if (getenv('HTTP_CLIENT_IP'))
                $ipaddress = getenv('HTTP_CLIENT_IP');
            else if(getenv('HTTP_X_FORWARDED_FOR'))
                $ipaddress = getenv('HTTP_X_FORWARDED_FOR');
            else if(getenv('HTTP_X_FORWARDED'))
                $ipaddress = getenv('HTTP_X_FORWARDED');
            else if(getenv('HTTP_FORWARDED_FOR'))
                $ipaddress = getenv('HTTP_FORWARDED_FOR');
            else if(getenv('HTTP_FORWARDED'))
                $ipaddress = getenv('HTTP_FORWARDED');
            else if(getenv('REMOTE_ADDR'))
                $ipaddress = getenv('REMOTE_ADDR');
            else
                $ipaddress = 'UNKNOWN';

        }catch (\Exception $e){

        }

        return $ipaddress;

    }

    public function verifyOtp(Request $request)
    {

        $mobile_number = $request->input('mobile_number');
        $request_id = $request->input('request_id');

        if (strlen($mobile_number) == 12 && substr($mobile_number, 0, 2) == "91") {
            $mobile_number = substr($mobile_number, 2, 10);
        }
        if($request_id != ""){
            User::where('mobile_number', $mobile_number)->update(['user_verified'=> 1]);
            $telecom = new TelecomDetails();
            $response = $telecom->verifyOtp($request_id,$request->input('otp'),'',$mobile_number);
            if($response == false){
                $otp           = rand('100000', '999999');
                //$message = "By validating OTP $otp I agree to Credit Fair's terms and conditions https://bit.ly/2QRVgjd for the loan application and have no objection to them conducting a credit check.<br/>Best Regards,<br/>Team Credit Fair";
                //$message = "By validating OTP ".$otp." I agree to Credit Fair's terms and conditions (https://bit.ly/2QRVgjd), for the loan application and have no objection to them conducting a credit check & sending notifications on Whatsapp";
                $message = "By validating OTP $otp I agree to Credit Fair's terms and conditions provided here - https://lnk.creditfair.in/hFVR, for the loan application and have no objection to them conducting a credit check";
                $templateId = Templates::$otp2;
                OtpManager::where('mobile_number', (string)$mobile_number)->delete();
                $otp_manager                = new \App\OtpManager();
                $otp_manager->otp           = $otp;
                $otp_manager->mobile_number = $mobile_number;
                $otp_manager->save();

                $mobile_number = '91' . $mobile_number;
                $entity = ['templateid' => '1307159980200805400', 'entityid' => Templates::$entityid];
                send_sms($mobile_number, ['message'=>$message, 'OTP' => true, 'templateId' => $templateId, 'args' => [$otp], 'templateDetails' => $entity]);

                $data['status']  = 'success';
                $data['message'] = 'OTP request sent';
                $data['request_id'] = "";
                return base64_encode(json_encode($data));
            }else{
                $data['status']  = 'success';
                $this->current_status = 'incomplete form';
                $data = $this->applicationSubmit($request);
                $data['message'] = 'OTP successfully verified';
                return response()->json($data);
            }
        }

        if (\App\OtpManager::where('mobile_number', (string)$mobile_number)->where('otp', $request->input('otp'))->first()) {

            \App\OtpManager::where('mobile_number', (string)$mobile_number)->delete();

            $data['status']  = 'success';
            $this->current_status = 'incomplete form';
            if (!$request->has('page_lp_event')) {
                $data = $this->applicationSubmit($request);
                User::where('mobile_number', $mobile_number)->update(['user_verified' => 1]);
            }
            $data['message'] = 'OTP successfully verified';
            return response()->json($data);
        } else {
            $data['status']  = 'failure';
            $data['message'] = 'OTP verification failed';
            return response()->json($data);
        }
    }

    public function getExistingCustomer(Request $request){
        $application = ConsumerApplication::find($request->get('id'));
        return response()->json(['data' => $application], 200);
    }

    public function isExistingCustomer(Request $request, $co_applicant = true){
        $applications = [];
        $application = [];
        if ($request->has('pan_card') || $request->has('email') || $request->has('mobile_number')) {
            if (!empty($request->get('pan_card'))) {
                $application[] = ConsumerApplication::where('pan_card', $request->get('pan_card'))->whereNull('is_deleted')->orderBy('created_at', 'desc')->get(['id', 'name', 'mobile_number', 'state', 'applicant_id']);
            }
            if (!empty($request->get('email'))) {
                $application[] = ConsumerApplication::where('email', $request->get('email'))->whereNull('is_deleted')->orderBy('created_at', 'desc')->get(['id', 'name', 'mobile_number', 'state', 'applicant_id']);
            }
            if (!empty($request->get('mobile_number'))) {
                $application[] = ConsumerApplication::where('mobile_number', $request->get('mobile_number'))->whereNull('is_deleted')->orderBy('created_at', 'desc')->get(['id', 'name', 'mobile_number', 'state', 'applicant_id']);
            }
        }
        // check in co-applicant details
        if ($co_applicant){
            if(!empty($request->get('pan_card'))) {
                $application[] = ConsumerApplication::where('co_applicant_pan_card', $request->get('pan_card'))->whereNull('is_deleted')->orderBy('created_at', 'desc')->get(['id','name','mobile_number','state','co_applicant_id']);
            }
            if(!empty($request->get('email'))) {
                $application[] = ConsumerApplication::where('co_applicant_email', $request->get('email'))->whereNull('is_deleted')->orderBy('created_at', 'desc')->get(['id','name','mobile_number','state','co_applicant_id']);
            }
            if(!empty($request->get('mobile_number'))) {
                $application[] = ConsumerApplication::where('co_applicant_mobile_number', $request->get('mobile_number'))->whereNull('is_deleted')->orderBy('created_at', 'desc')->get(['id','name','mobile_number','state','co_applicant_id']);
            }
        }


        if ($application){
            foreach ($application as $item){
                foreach ($item as $_item) {
                    if (!in_array($_item->id, $applications))
                        $applications[] = [
                            'id' => $_item->id,
                            'name' => $_item->name,
                            'mobile_number' => $_item->mobile_number,
                            'status' => $_item->state,
                            'applicant_id' => isset($_item->applicant_id) && $_item->applicant_id ? $_item->applicant_id : (isset($_item->co_applicant_id) && !empty($_item->co_applicant_id) ? $_item->co_applicant_id : 0)
                        ];
                }
            }
        }
        $cwFactory = new CloudWatchLoggerFactory();
        $cwFactory->logger(json_encode([
            'action' => 'isExistingCustomer_END',
            'matches_found_count' => count($applications),
            'matches_data' => $applications, // This will show you exactly what ID was returned
            'message' => 'Returning potential existing matches'
        ]));

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

    public function checkEligibility(Request $request, $isCoApplicant = false){
        //return $application = 0;
        $repeatPeriod = Carbon::now()->subMonth(3)->toDateTimeString();
        if($request->has('pan')  || $request->has('email') || $request->has('mobile_number')||$request->has('aadhaar_card')){
            if(!empty($request->get('pan'))) {
                $application = ConsumerApplication::where('pan_card', $request->get('pan'))->where('created_at', '>=', $repeatPeriod)->whereNull('is_deleted')->orderBy('created_at', 'desc')->first(['id']);
            }
            if(!empty($request->get('email'))) {
                if (!isset($application->id)) {
                    $application = ConsumerApplication::where('email', $request->get('email'))->where('created_at', '>=', $repeatPeriod)->whereNull('is_deleted')->orderBy('created_at', 'desc')->first(['id']);
                }
            }
            if(!empty($request->get('mobile_number'))) {
                if (!isset($application->id)) {
                    $application = ConsumerApplication::where('mobile_number', $request->get('mobile_number'))->where('created_at', '>=', $repeatPeriod)->whereNull('is_deleted')->orderBy('created_at', 'desc')->first(['id']);
                }
            }
            if(!empty($request->get('aadhaar_card'))) {
                if (!isset($application->id)) {
                    $application = ConsumerApplication::where('aadhaar_card', $request->get('aadhaar_card'))->where('created_at', '>=', $repeatPeriod)->whereNull('is_deleted')->orderBy('created_at', 'desc')->first(['id']);
                }
            }

            if(isset($application->id)) {
                $this->current_status = 'rejected';
                return $application->id;
            }
        }
        if ($isCoApplicant){
            if(!empty($request->get('pan'))) {
                $application = ConsumerApplication::where('co_applicant_pan_card', $request->get('pan'))->where('created_at', '>=', $repeatPeriod)->whereNull('is_deleted')->orderBy('created_at', 'desc')->first(['id']);
            }
            if(!empty($request->get('email'))) {
                if (!isset($application->id)) {
                    $application = ConsumerApplication::where('co_applicant_email', $request->get('email'))->where('created_at', '>=', $repeatPeriod)->whereNull('is_deleted')->orderBy('created_at', 'desc')->first(['id']);
                }
            }
            if(!empty($request->get('mobile_number'))) {
                if (!isset($application->id)) {
                    $application = ConsumerApplication::where('co_applicant_mobile_number', $request->get('mobile_number'))->where('created_at', '>=', $repeatPeriod)->whereNull('is_deleted')->orderBy('created_at', 'desc')->first(['id']);
                }
            }
            if(!empty($request->get('aadhaar_card'))) {
                if (!isset($application->id)) {
                    $application = ConsumerApplication::where('co_applicant_aadhaar_card', $request->get('aadhaar_card'))->where('created_at', '>=', $repeatPeriod)->whereNull('is_deleted')->orderBy('created_at', 'desc')->first(['id']);
                }
            }

            if(isset($application->id)) {
                $this->current_status = 'rejected';
                return $application->id;
            }
        }
        return 0;
    }

    public function coPartnerSubmit(Request $request){
        $hashids = new Hashids('Creditfair by CS', 20);
        $user_id = $request->has('user_id') ? $hashids->decode($request->get('user_id'))[0] : '';

        if($user_id) {

            $existingApplication = $this->checkEligibility($request);

            if ($this->current_status == 'rejected' && $existingApplication != 0) {
                $time = (new MerchantApiController())->getRemainingMonths($existingApplication);
                $data['status'] = 'Failed';
                $data['message'] = 'It seems like it has been less than 3 months since you applied to Credit Fair . We will be happy to serve you after ' . $time . ' Month';
                return response()->json($data);
            }

            $pan = $request->input('pan');
            if($pan == '' || PWAApplicationForm::pan_format_validation($request->input('pan')) != "Valid"){
                $data['status'] = 'Failed';
                $data['message'] = 'Please enter a Valid Pan Number';
                return response()->json($data);
            }

            $mobile_number = $request->input('mobile_number');
            if (strlen($mobile_number) == 12 && substr($mobile_number, 0, 2) == "91") {
                $mobile_number = substr($mobile_number, 2, 10);
            }

            //Create User
            $user = \App\User::where('mobile_number', $mobile_number)->where('user_type', 'consumer')->first();
            if (!$user) {
                $user = new \App\User();
            }

            $name = $request->get('first_name').' '.$request->get('last_name');

            $user->fill($request->input());
            $user->name = $name;
            $user->user_type = 1;
            $user->save();

            //Create Application
            $consumer_application = new \App\ConsumerApplication();
            $consumer_application->fill($request->input());
            $consumer_application->user_id = $user->id;
            $consumer_application->name = $name;
            $consumer_application->pan_card = $request->get('pan');
            if ($request->has('offer_id') && $request->get('offer_id')) {
                $merchantOffer = MerchantOffers::where('id', $request->get('offer_id'))->first(['merchant_id']);
                $merchant_id = $merchantOffer->merchant_id ?? '';
                $consumer_application->merchant_id = $merchant_id;
            }

            $consumer_application->state = 'incomplete form';
            $consumer_application->completed_stage = 0;
            $consumer_application->updated_by = 'co-partner';
            $customer = $consumer_application->saveCustomer();
            $consumer_application->applicant_id = $customer->applicant_id;
            $consumer_application->lender_id = 2;
            $consumer_application->co_applicant_id = $customer->co_applicant_id;
            $consumer_application->save();

            // send communication on incomplete form for new user
            if(!((new ConsumerApplicationController())->isExistingCustomer($consumer_application->id))){
                (new TestingController())->incompleteFormCommunication($consumer_application->id, true);
            }

//            (new ConsumerApplicationController())->sendMessageOnWhatsApp($consumer_application->id, 'website', 'both');

            $consumer_application_elements = new ConsumerApplicationElement();
            $consumer_application_elements->application_id = $consumer_application->id;
            $consumer_application_elements->preferred_language = strtoupper($request->get('preferred_language'));
            $consumer_application_elements->center_id = $request->has('merchant_location_id') ? $request->get('merchant_location_id') : ($request->has('center') ? $request->get('center') : 0);
            $consumer_application_elements->unique_id_number = $request->get('unique_id_number');
            $consumer_application_elements->save();

            if ($name && isset($customer->applicant_id)) {
                PWAApplicationForm::sendVerificationEmail($request->get('name'), $customer->applicant_id);
            }

            StatusLogs::insert([
                'application_id' => $consumer_application->id,
                'user_id' => $user_id,
                'status' => 'incomplete form',
                'created_at' => Carbon::now()->toDateTimeString()
            ]);

            $data['status'] = 'success';
            $data['application_id'] = $consumer_application->id;
            $data['message'] = 'Application Submited successfully';
            $consumer_application_controller = new ConsumerApplicationController();
            $consumer_application_controller->sendslackmessage($consumer_application->id, 'incomplete form', '','','',true);

            $consumer_application_controller->waitReminder($consumer_application->id);

            return response()->json($data);
        }
    }

    public function applicationSubmit(Request $request)
    {

        $data['error']['eligibility'] = $this->checkEligibility($request);

        if ($this->current_status == 'rejected'){
            return $data;
        }

        $mobile_number = $request->input('mobile_number');
        if (strlen($mobile_number) == 12 && substr($mobile_number, 0, 2) == "91") {
            $mobile_number = substr($mobile_number, 2, 10);
        }

        $user = \App\User::where('mobile_number', $mobile_number)->where('user_type', 'consumer')->first();
        if (!$user) {
            $user = new \App\User();
        }
        $user->fill($request->input());
        $user->user_type = 1;
        $user->save();

        $consumer_application = new \App\ConsumerApplication();
        $consumer_application->fill($request->input());

        if (strlen($mobile_number) == 12 && substr($mobile_number, 0, 2) == "91") {
            $consumer_application->mobile_number = substr($mobile_number, 2, 10);
        }

        $consumer_application->user_id         = $user->id;
        if($request->has('offer_id') && $request->get('offer_id')) {
            $merchantOffer = MerchantOffers::where('id', $request->get('offer_id'))->first(['merchant_id']);
            $merchant_id = isset($merchantOffer->merchant_id) ? $merchantOffer->merchant_id : '';
            $consumer_application->merchant_id = $merchant_id;
            /*if($merchant_id == 5803){
                $consumer_application->loan_amount = 10000;
            }*/
        }

        /*if($request->get('merchant_id') == 5803){
            $consumer_application->loan_amount = 10000;
        }*/

        $consumer_application->state           = $this->current_status;
        $consumer_application->completed_stage = 0;
        $consumer_application->updated_by      = $request->has('api_init') ? 'website-api' : 'website';


        $customer = $consumer_application->saveCustomer();
        $consumer_application->applicant_id = $customer->applicant_id;
        $consumer_application->lender_id = 2;
        $consumer_application->co_applicant_id = $customer->co_applicant_id;

        $consumer_application->save();

        // send communication on incomplete form for new user
        if(!((new ConsumerApplicationController())->isExistingCustomer($consumer_application->id))){
            (new TestingController())->incompleteFormCommunication($consumer_application->id, true);
        }

        (new ConsumerApplicationController())->sendMessageOnWhatsApp($consumer_application->id, 'website', 'both');

        if($request->get('name')) {
            //$request->attributes->add(['title' => $request->get('name') . ' (' . $request->get('mobile_number') . ')']);
            //(new Trello($request))->insertInTrello();
        }
        $consumer_application_elements = new ConsumerApplicationElement();
        $consumer_application_elements->application_id = $consumer_application->id;
        $consumer_application_elements->preferred_language = strtoupper($request->input('preferred_language'));
        $consumer_application_elements->center_id = $request->has('merchant_location_id') ? $request->get('merchant_location_id') : ($request->has('center_id') ? $request->get('center_id') : 0);
        $consumer_application_elements->product_id = isset($request->product_id) ? $request->product_id : '';
        $consumer_application_elements->product_name = isset($request->product_name) ? $request->product_name : '';
        $consumer_application_elements->duration = isset($request->duration_year) && isset($request->duration_month) ? $request->duration_month.'|'.$request->duration_year : '';
        $consumer_application_elements->unique_id_number = $request->input('unique_id_number');
        if(!empty($telecom_response)){
            $consumer_application_elements->telecom_response = $telecom_response;
        }

        if($request->has('inverter') || $request->has('panel')){
            if($request->get('inverter') == 'other'){
                $inverterName = $request->get('other_inverter');
            }else{
                $inverterName = $request->get('inverter');
            }
            $consumer_application_elements->inverter = $inverterName;

            if($request->get('panel') == 'other'){
                $panelName = $request->get('other_panel');
            }else{
                $panelName = $request->get('panel');
            }
            $consumer_application_elements->panel = $panelName;

            $consumer_application_elements->inverter_model_description =$request->has('model_description') ? $request->get('model_description') : null;
            $consumer_application_elements->inverter_monthly_power_bill =$request->get('KW_installation');
            $consumer_application_elements->type_of_customer =$request->get('type_of_customer');
            $consumer_application_elements->solar_power_type =$request->get('type_of_solar_power');
            $consumer_application_elements->inverter_KW_installation =$request->get('monthly_power_bill');
            $consumer_application_elements->inverter_gross_project_amount =$request->get('gross_project_amount');
            $consumer_application_elements->inverter_subsidy_amount =$request->get('subsidy_amount');
            $consumer_application_elements->inverter_power_savings = $request->get('power_savings');
        }

        $consumer_application_elements->save();

        if($this->current_status == 'incomplete form' || $this->current_status == 'rejected') {

            if ($this->current_status == 'incomplete form'){
                if ($request->get('name') && isset($customer->applicant_id)) {
                    PWAApplicationForm::sendVerificationEmail($request->get('name'), $customer->applicant_id);
                }
                if ($request->get('co_applicant_name') && isset($customer->co_applicant_id)) {
                    PWAApplicationForm::sendVerificationEmail($request->get('co_applicant_name'), $customer->co_applicant_id);
                }
            }

            StatusLogs::insert([
                'application_id' => $consumer_application->id,
                'user_id' => $this->current_status == 'incomplete form' ? $user->id : 107,
                'status' => $this->current_status,
                'created_at' => Carbon::now()->toDateTimeString()
            ]);
            //EMAIL notification
            /*if (_env('NOTIFY_EMAIL', '')) {
                $mail_data = $consumer_application->toArray();
                $mail_data['merchant_name'] = "Credit Fair";

                \Mail::send('emails.customer-loan-admin-notification', $mail_data
                    ,function ($message) use ($mail_data) {
                        $message->to(_env('NOTIFY_EMAIL', ''), 'Credit Fair Support')->subject
                        ('[Credit Fair]New Application Submitted by ' . $mail_data['name']);
                    });
            }*/
        }

        if($request->get('loan_amount')){
            $this->updateStatus($user->id, $consumer_application->id, 'in-process');
        }

        $hashids = new Hashids('Creditfair by CS', 20);

        $data['status']         = 'success';
        $data['hashed_id']      = $hashids->encode($consumer_application->id);
        $data['application_id'] = $consumer_application->id;
        $data['message']        = 'Application Submitted successfully';
        $consumer_application_controller = new ConsumerApplicationController();
        $consumer_application_controller->sendslackmessage($consumer_application->id,'form completed');

        $consumer_application_controller->waitReminder($consumer_application->id);

        if($this->current_status == 'incomplete form' || $this->current_status == 'rejected'){
            return $data;
        }
        if ($consumer_application->state === 'form completed') {
            // application status changed to form completed
            try {
                event(new EventPostFormCompleted($consumer_application->id));
            }catch (\Exception $e){

            }
        }
        return response()->json($data);
    }

    public function updateStatus($user_id, $id, $status){
        $application = ConsumerApplication::where('id', $id)->where('state', $status)->first(['id']);
        if(!isset($application->id)){
            ConsumerApplication::where('id', $id)->update(['state' => $status]);

            StatusLogs::insert([
                'application_id' => $id,
                'user_id' => $user_id,
                'status' => $status,
                'created_at' => Carbon::now()->toDateTimeString()
            ]);
        }
    }

    public function initExotel(Request $request){
        try {
            $from_mobile = $request->get('CallFrom');
            $to_mobile = $request->get('CallTo');
            $from_mobile = strlen($from_mobile) == 11 ? trim($from_mobile, '0') : (strlen($from_mobile) == 12 ? substr($from_mobile, 2) : $from_mobile);
            $data = $this->getMobileData($from_mobile);

            CallLogs::insert([
                'user_id' => 0,
                '_id' => $data['id'],
                'id_type' => $data['type'],
                'to' => $to_mobile,
                'from' => $from_mobile,
                'message' => "",
                'error' => "",
                'purpose' => "Incoming Call",
                'description' => json_encode($request->all()),
                'sid' => $request->get('CallSid'),
                'created_at' => Carbon::now()->toDateTimeString()
            ]);

            return response()->json(['status' => 'OK'], 200);
        }catch (\Exception $e){
            (new \App\Slack(new \Illuminate\Http\Request(['title'=>'Exotel Error Error','fields'=>['error'=>$e->getMessage(),'line'=>$e->getLine(),'trace'=>$e->getTraceAsString()]])))->send();
            return response()->json(['status' => 'OK'], 200);
        }

    }

    public function getMobileData($from_mobile, Request $request = null){
        $id = 0;
        $type = "unknown";
        $isfound = 0;
        $user_id = 0;
        $rm_user_id = 0;
        $name = '';
        $consumer = ConsumerApplication::with('merchant')->where(function ($query) use ($from_mobile) {
            $query->where('mobile_number', $from_mobile)
                ->orWhere('co_applicant_mobile_number', $from_mobile)
            ;
        })->whereNull('is_deleted')->first();
        if ($consumer) {
            if ($consumer->mobile_number == $from_mobile) {
                $name = $consumer->name;
                $id = $consumer->id;
                $type = "application_id";
                $isfound = 1;
            } elseif ($consumer->co_applicant_mobile_number == $from_mobile) {
                $name = $consumer->co_applicant_name;
                $id = $consumer->id;
                $type = "application_id";
                $isfound = 1;
            }

            $rm_user_id = (isset($consumer->merchant) && isset($consumer->merchant->rm_exotel[0])) ? $consumer->merchant->rm_id : 0;
        }

        if ($isfound == 0) {
            $users = User::where('mobile_number', $from_mobile)->first(['id', 'name', 'user_type', 'merchant_id']);
            if ($users) {
                if ($users->user_type == 2 || $users->user_type == 3 || $users->user_type == 4) {
                    $name = $users->name;
                    $id = $users->merchant_id;
                    $type = "merchant_id";
                    $isfound = 1;
                    $user_id = $users->id;
                }
                if (isset($users->merchant_id) && $users->merchant_id > 0) {
                    $_rm_id = Merchant::with('rm_exotel')->where('id',$users->merchant_id)->first(['rm_id']);
                    $rm_user_id = isset($_rm_id->rm_id) && $_rm_id->rm_id && isset($_rm_id->rm_exotel->id)? $_rm_id->rm_id : 0;
                }
            }
        }

        if ($isfound == 0) {
            $merchant = Merchant::where('contact_number', 'like', '%' . $from_mobile . '%')->orwhere('rcp_mobile', 'like', '%' . $from_mobile . '%')->orwhere('sales_head_mobile', 'like', '%' . $from_mobile . '%')->orwhere('finance_head_mobile', 'like', '%' . $from_mobile . '%')->first();
            if ($merchant) {
                if ($merchant->contact_number == $from_mobile) {
                    $name = $merchant->merchant_name;
                    $id = $merchant->id;
                    $type = "merchant_id";
                    $isfound = 1;
                } elseif ($merchant->rcp_mobile == $from_mobile) {
                    $name = $merchant->rcp;
                    $id = $merchant->id;
                    $type = "merchant_id";
                    $isfound = 1;
                } elseif ($merchant->sales_head_mobile == $from_mobile) {
                    $name = $merchant->sales_head;
                    $id = $merchant->id;
                    $type = "merchant_id";
                    $isfound = 1;
                } elseif ($merchant->finance_head_mobile == $from_mobile) {
                    $name = $merchant->finance_head;
                    $id = $merchant->id;
                    $type = "merchant_id";
                    $isfound = 1;
                }

                $rm_user_id = $merchant->rm_id ? $merchant->rm_id : 0;
            }
        }

        if ($isfound == 0) {
            $center = MerchantLocation::with('merchant')->where('phone', 'like', '%' . $from_mobile . '%')->first();
            if ($center) {
                if ($center->phone == $from_mobile) {
                    $name = $center->name;
                    $id = $center->merchant_id;
                    $type = "merchant_id";
                    $isfound = 1;
                    $rm_user_id = $center->merchant ? $center->merchant->rm_id : 0;
                }
            }
        }

        return ['name' => $name, 'id' => $id, 'type' => $type, 'user_id' => $user_id, 'rm_user_id' => $request && $request->get('dep') !=2 ? $rm_user_id : 0];
    }

    public function routingExotel(Request $request){
        try {
            if ($request->get('type') && $from_mobile = $request->has('CallFrom')) {
                $from_mobile = $request->get('CallFrom');
                $from_mobile = strlen($from_mobile) == 11 ? trim($from_mobile, '0') : (strlen($from_mobile) == 12 ? substr($from_mobile, 2) : $from_mobile);
                $data = $this->getMobileData($from_mobile);
                $whoIs = 'unknown';
                switch ($request->get('type')) {
                    case 1: // customer
                        $whoIs = 'Customer';
                        switch ($request->get('enquiretype')) {
                            case 1: // current loan status
                                $whatIs = 'Current Loan Status';
                                switch ($request->get('stage')) {
                                    case 1: // advisors
                                        if (isset($data['type']) && $data['type'] == 'application_id' && $data['id'] > 0) {
                                            $application = ConsumerApplication::find($data['id']);
                                            if (isset($application->created_by)) {
                                                $user_id = [$application->created_by];
                                            }

                                        }

                                        if (!isset($user_id)) {
                                            $user_id = [29, 36];
                                        }

                                        break;
                                    case 2: // rohit & mahima
                                        $user_id = [519, 598];
                                        break;

                                }
                                break;
                            case 2: // repayment
                                $whatIs = 'Repayment';
                                switch ($request->get('stage')) {
                                    case 1: //rajendra
                                        $user_id = [543];
                                        break;
                                    case 2: // imran
                                        $user_id = [251];
                                        break;
                                }
                                break;
                            case 3: // new application
                                $whatIs = 'New Application';
                                switch ($request->get('stage')) {
                                    case 1: //rohit
                                        $user_id = [519];
                                        break;
                                    case 2: //mahima
                                        $user_id = [598];
                                        break;
                                }
                                break;
                        }
                        break;
                    case 2: // merchant
                        $whoIs = 'Merchant';
                        switch ($request->get('enquiretype')) {
                            case 1: // application status
                                $whatIs = 'Application Status';
                                switch ($request->get('stage')) {
                                    case 1: // rohit
                                        $user_id = [519];
                                        break;
                                    case 2: // mahima
                                        $user_id = [598];
                                        break;
                                }
                                break;
                            case 2: // new merchant
                                $whatIs = 'New Merchant';
                                switch ($request->get('stage')) {
                                    case 1: // ashwini
                                        $user_id = [4];
                                        break;
                                    case 2: // piyush
                                        $user_id = [10];
                                        break;
                                }
                                break;
                        }
                        break;
                    case 3: // collection
                        switch ($request->get('enquiretype')) {
                            case 1: // general flow
                                switch ($request->get('stage')) {
                                    case 1: // rajendra
                                        $user_id = [543];
                                        break;
                                    case 2: // imran
                                        $user_id = [251];
                                        break;
                                }
                                break;
                        }
                        break;
                }


                if (empty($data['name'])) {
                    $data['name'] = isset($whoIs) ? $whoIs : '';
                }
                $data['update'] = isset($whatIs) ? $whatIs : '';

                if ($request->get('CallSid') && isset($whatIs)) {
                    $received_by = isset($user_id) && count($user_id) == 1 ? $user_id[0] : 0;
                    CallLogs::where('sid', $request->get('CallSid'))->update(['purpose' => $whoIs . ' called for ' . $whatIs,'user_id' => $received_by]);
                }

                $consumerApplication = new ConsumerApplicationController();
                if (isset($user_id)) {
                    $number = [];
                    $users = User::whereIn('id', $user_id)->get(['mobile_number', 'id']);
                    foreach ($users as $user) {
                        $number[] = $user->mobile_number;
                        $gcmRegistration = GCMRegistraion::where('user_id', $user->id)->first(['id']);
                        if (isset($gcmRegistration->id)) {
                            //$consumerApplication->callerInformation($user->id, $data);
                        } else {
                            //sendWhatsAppMessage($user->mobile_number, 'Hi, ' . $data['name'] . ' is calling you regarding ' . $data['update']);
                        }
                        return response()->json(implode(',', $number), 200);
                    }
                }
            }
        }catch (\Exception $e){
            (new \App\Slack(new Request(['title'=>'Exotel Error (Incoming call)','fields'=>['error'=>$e->getMessage(),'line'=>$e->getLine(),'trace'=>$e->getTraceAsString()]])))->send();
        }
    }

    public function getAdvisorID($data){
        $user_id = [];
        if (isset($data['type']) && $data['type'] == 'application_id' && $data['id'] > 0) {
            $application = ConsumerApplication::with('advisor')->find($data['id']);
            if (isset($application->created_by) && isset($application->advisor) && $application->advisor->user_availability == 1 && $application->advisor->deleted_at == null) {
                $user_id = [$application->created_by];
            }
        }
        return $user_id;
    }

    public function getRoute(Request $request, $list, $level){
        $user_id = 0;
        $from_mobile = $request->get('CallFrom');
        $from_mobile = strlen($from_mobile) == 11 ? trim($from_mobile, '0') : (strlen($from_mobile) == 12 ? substr($from_mobile, 2) : $from_mobile);
        $data = $this->getMobileData($from_mobile, $request);
        $list[0] = 0;
        $list[1] = $data['rm_user_id'];
        ksort($list);
        if($data['type'] == 'application_id'){
            $whoIs = 'Customer';
            switch ($request->get('stage')) {
                case 1:
                    $user_id = $level == 1 ? $this->getAdvisorID($data) : [];
                    if (!$user_id){
                        $new_list = $list;
                        foreach (array_values($new_list) as $item) {
                            if ($item && (!in_array($item, $this->getAdvisorID($data)))) {
                                $user_id = $item;
                                break;
                            }
                        }
                    }
                    if (is_array($user_id))
                        $user_id = $user_id[0];
                    break;
                default:
                    if($request->get('dep') != 1)
                        $list = array_filter($list);
                    $new_list = $list;
                    if ($request->get('dep') == 1 && $list[1] == 0) {
                        $new_list = array_slice($new_list, ($request->get('stage')));
                    }else{
                        $new_list = array_slice($new_list,($request->get('stage') - 1));
                    }
                    foreach (array_values($new_list) as $item) {
                        if ($item && !in_array($item, $this->getAdvisorID($data))) {
                            $user_id = $item;
                            break;
                        }
                    }
                    break;
            }
        }else{
            $whoIs = $data['type'] == 'merchant_id' ? 'Merchant' : 'Unknown';
            switch ($request->get('stage')) {
                default:
                    if(!$list[0]){
                        unset($list[0]);
                    }
                    if(!$list[1]){
                        //unset($list[1]);
                    }
                    $new_list = $list;
                    $new_list = array_slice($new_list,($request->get('stage')));
                    foreach (array_values($new_list) as $item) {
                        if ($item) {
                            $user_id = $item;
                            break;
                        }
                    }
                    break;
            }
        }

        return ['whoIs' => isset($data['name']) && !empty($data['name']) ? $data['name'] : $whoIs, 'user_id' => $user_id];
    }

    public function getLastCalledByUser($list, Request $request){
        $listOLD = $listNew = $list;
        $from_mobile = $request->get('CallFrom');
        $from_mobile = strlen($from_mobile) == 11 ? trim($from_mobile, '0') : (strlen($from_mobile) == 12 ? substr($from_mobile, 2) : $from_mobile);
        $log = CallLogs::where('to', $from_mobile)->orderBy('created_at','desc')->first(['user_id']);
        if ($log && $log->user_id) {
            array_unshift($list, $log->user_id);
            array_push($listOLD, $log->user_id);
            $i = 0;
            foreach ($listOLD as $key => $item){
                $listNew[$key] = (int)$list[$i];
                $i++;
            }
        }

        return $listNew;
    }

    public function getListAccordingToAvailability($list, Request $request){
        $listData = [];
        $list = $this->getLastCalledByUser($list, $request);
        $userLists = User::whereIn('id', $list)->where('user_availability', 1)->get(['id']);
        $activeLists = [];

        foreach ($userLists as $listItem){
            $activeLists[] = $listItem->id;
        }


        foreach ($list as $key => $item){
            if(!in_array($item, $activeLists)){
                unset($list[$key]);
            }
        }

        $listSend = [];
        $keyItem = 0;
        foreach ($list as $itemView){
            $listSend[$keyItem + 2] = $itemView;
            $keyItem++;
        }
        /*foreach ($userLists as $_key_v => $_list_id){
            if ($list[array_search($_list_id->id, $list)]){
                $listData[($_key_v + 2)] = $_list_id->id;
                $vm[] = $_list_id->id;
            }
        }*/
        /*$k = array_keys($listData);
        $v = array_values($listData);
        $rv = array_reverse($v);
        $listData = array_combine($k, $rv);
        if($listData[2] && in_array($list[2], $vm)){
            $one = $listData[2];
            $position = array_search($list[2],$listData);
            $listData[2] = $list[2];
            $listData[$position] = $one;
        }

        return $listData;*/
        return $listSend;
    }

    public function routingExotelV1(Request $request){

        /*$dep = [
            1 => 'customer support',
            2 => 'collection',
            3 => 'bd'
        ];*/

        $level = 1;

        if ($request->get('dep') == 1){
            $list = [

                1 => 144474, // Kshitija Botle
                2 => 144699, // Rukmani rajbhar
                // 3 => 80316, // fathima
                // 4 => 131876, // Pooja Barolia
                // 5 => 75924, //Harshala
                // 6 => 31045, //Tarun Mistry
            ];

        }elseif ($request->get('dep') == 2){
            $level = 2;
            $list = [
                //2 => 1950,//Archana
                2 => 543, //Rajendra
                3 => 251, //imran
            ];
        }elseif ($request->get('dep') == 3){
            $level = 3;
            $list = [
                2 => 2020,//darshan
                3 => 10, //piyush
            ];
        }elseif ($request->get('dep') == 4){
            $level = 4;
            $list = [
                2 => 23183,//rahil
                3 => 598,//mahima
                4 => 10, //piyush
            ];
        }

        if (isset($list)) {
            $list = $this->getListAccordingToAvailability($list, $request);
        }

        try {
            if ($from_mobile = $request->has('CallFrom') && isset($list) && $list) {

                $route = $this->getRoute($request, $list, $level);

                $whoIs = $route['whoIs'];
                $user_id = $route['user_id'];

                if (empty($data['name'])) {
                    $data['name'] = isset($whoIs) ? $whoIs : '';
                }
                $data['update'] = isset($whatIs) ? ' regarding '.$whatIs : '';

                if ($request->get('CallSid') && isset($whatIs)) {
                    $received_by = isset($user_id) ? $user_id : 0;
                    CallLogs::where('sid', $request->get('CallSid'))->update(['purpose' => $whoIs . ' called for ' . $whatIs,'user_id' => $received_by]);
                }

                $consumerApplication = new ConsumerApplicationController();
                if (isset($user_id) && $user_id) {
                    $number = [];
                    $users = User::where('id', $user_id)->whereNull('deleted_at')->get(['mobile_number', 'id','name']);
                    foreach ($users as $user) {
                        $number[] = $user->mobile_number;
                        $gcmRegistration = GCMRegistraion::where('user_id', $user->id)->where('status','active')->where('device_type','android')->first(['id']);
                        if (isset($gcmRegistration->id)) {
                            $consumerApplication->callerInformation($user->id, $data);
                        } else {
                            sendWhatsAppMessage($user->mobile_number, 'Hi, ' . $data['name'] . ' is calling you' . $data['update']);
                        }
                        //(new Slack(new Request(['title'=>'Exotel Testing (Incoming call)','fields'=>['data'=>json_encode($request->all()), 'to' => implode(',', $number)]])))->send();
                        return response()->json(implode(',', $number), 200);
                    }
                }
            }
        }catch (\Exception $e){
            (new Slack(new Request(['title'=>'Exotel Error (Incoming call)','fields'=>['error'=>$e->getMessage(),'line'=>$e->getLine(),'trace'=>$e->getTraceAsString()]])))->send();
        }
    }

    public function routingExotelNew(Request $request){
        try {
            if ($from_mobile = $request->has('CallFrom')) {
                $from_mobile = $request->get('CallFrom');
                $from_mobile = strlen($from_mobile) == 11 ? trim($from_mobile, '0') : (strlen($from_mobile) == 12 ? substr($from_mobile, 2) : $from_mobile);
                $data = $this->getMobileData($from_mobile);
                if(isset($data['type'])){
                    if($data['type'] == 'application_id'){
                        $whoIs = 'Customer';
                        switch ($request->get('stage')) {
                            case 1: // advisors
                                if (isset($data['type']) && $data['type'] == 'application_id' && $data['id'] > 0) {
                                    $application = ConsumerApplication::find($data['id']);
                                    if (isset($application->created_by)) {
                                        $user_id = [$application->created_by];
                                    }

                                }

                                break;
                            case 2: // rohit
                                $user_id = [598];
                                (new Slack(new Request(['title'=>'Exotel (Incoming call)','fields'=>['status'=>'Advisor missed the call','mobile'=> $request->get('CallFrom')]])))->send();
                                //$user_id = [598];//mahima
                                break;
                            case 3: // mahima
                                (new Slack(new Request(['title'=>'Exotel (Incoming call)','fields'=>['status'=>'Mahima missed the call','mobile'=> $request->get('CallFrom')]])))->send();
                                //$user_id = [598];
                                $user_id = [6];//shraddha
                                break;
                        }
                    }elseif($data['type'] == 'merchant_id'){
                        $whoIs = 'Merchant';
                        switch ($request->get('stage')) {
                            case 1: // mahima
                                $user_id = [598];
//                                if ($from_mobile == 8291919036){
//                                    $user_id = [27];
//                                }
                                //$user_id = [598];
                                break;
                            case 2: // mahima
                                //$user_id = [598];
                                $user_id = [6]; // Shraddha
//                                if ($from_mobile == 8291919036){
//                                    $user_id = [226];
//                                    (new Slack(new Request(['title'=>'Exotel (Incoming call)','fields'=>['status'=>'Sunil missed the call','mobile'=> $request->get('CallFrom')]])))->send();
//                                }else{
                                (new Slack(new Request(['title'=>'Exotel (Incoming call)','fields'=>['status'=>'Mahima missed the call','mobile'=> $request->get('CallFrom')]])))->send();
//                                }
                                break;
                            case 3: // ashwini
                                $user_id = [4];
//                                if ($from_mobile == 8291919036){
//                                    $user_id = [1510];
//                                    (new Slack(new Request(['title'=>'Exotel (Incoming call)','fields'=>['status'=>'Sarah missed the call','mobile'=> $request->get('CallFrom')]])))->send();
//                                }else{
                                (new Slack(new Request(['title'=>'Exotel (Incoming call)','fields'=>['status'=>'Mahima missed the call','mobile'=> $request->get('CallFrom')]])))->send();
//                                }
                                break;
                        }
                    }else{
                        $whoIs = 'Unknown';
                        switch ($request->get('stage')) {
                            case 1: // Mahima
                                $user_id = [598];
                                //$user_id = [598]; // Mahima
                                break;
                            case 2: // mahima
                                //$user_id = [598];
                                (new Slack(new Request(['title'=>'Exotel (Incoming call)','fields'=>['status'=>'Mahima missed the call','mobile'=> $request->get('CallFrom')]])))->send();
                                $user_id = [6]; // Shraddha
                                break;
                            case 3: // ashwini
                                (new Slack(new Request(['title'=>'Exotel (Incoming call)','fields'=>['status'=>'Shraddha missed the call','mobile'=> $request->get('CallFrom')]])))->send();
                                $user_id = [4];
                                break;
                        }

                    }
                }else{
                    $whoIs = 'Unknown';
                    switch ($request->get('stage')) {
                        case 1: // rohit
                            $user_id = [598];
                            //$user_id = [598]; // Mahima
                            break;
                        case 2: // mahima
                            //$user_id = [598];
                            (new Slack(new Request(['title'=>'Exotel (Incoming call)','fields'=>['status'=>'Mahima missed the call','mobile'=> $request->get('CallFrom')]])))->send();
                            $user_id = [6]; // Shraddha
                            break;
                        case 3: // ashwini
                            (new Slack(new Request(['title'=>'Exotel (Incoming call)','fields'=>['status'=>'Shraddha missed the call','mobile'=> $request->get('CallFrom')]])))->send();
                            $user_id = [4];
                            break;
                    }

                }
                if (empty($data['name'])) {
                    $data['name'] = isset($whoIs) ? $whoIs : '';
                }
                $data['update'] = isset($whatIs) ? ' regarding '.$whatIs : '';

                if ($request->get('CallSid') && isset($whatIs)) {
                    $received_by = isset($user_id) && count($user_id) == 1 ? $user_id[0] : 0;
                    CallLogs::where('sid', $request->get('CallSid'))->update(['purpose' => $whoIs . ' called for ' . $whatIs,'user_id' => $received_by]);
                }

                $consumerApplication = new ConsumerApplicationController();
                if (isset($user_id)) {
                    $number = [];
                    $users = User::whereIn('id', $user_id)->get(['mobile_number', 'id']);
                    foreach ($users as $user) {
                        $number[] = $user->mobile_number;
                        $gcmRegistration = GCMRegistraion::where('user_id', $user->id)->where('status','active')->where('device_type','android')->first(['id']);
                        if (isset($gcmRegistration->id)) {
                            $consumerApplication->callerInformation($user->id, $data);
                        } else {
                            sendWhatsAppMessage($user->mobile_number, 'Hi, ' . $data['name'] . ' is calling you' . $data['update']);
                        }
                        return response()->json(implode(',', $number), 200);
                    }
                }
            }
        }catch (\Exception $e){
            (new \App\Slack(new Request(['title'=>'Exotel Error (Incoming call)','fields'=>['error'=>$e->getMessage(),'line'=>$e->getLine(),'trace'=>$e->getTraceAsString()]])))->send();
        }
    }


    public function applicationUpdate(Request $request)
    {
        $consumer_application = "";
        if ($request->has('application_id')) {
            $consumer_application = \App\ConsumerApplication::find($request->input('application_id'));
        }
        if ($consumer_application) {


            // if ($request->has('unique_id_number') && $request->get('unique_id_number')) {
            //     ConsumerApplicationElement::where('application_id', $request->input('application_id'))->update(['unique_id_number' => $request->get('unique_id_number')]);
            // }
            $cae = ConsumerApplicationElement::where('application_id', $request->input('application_id'))->first();

            if(isset($cae->id)){
                $cae->preferred_language = strtoupper($request->input('preferred_language'));
                $cae->center_id = $request->has('merchant_location_id') ? $request->get('merchant_location_id') : ($request->has('center_id') ? $request->get('center_id') : 0);
                $cae->product_id = $request->has('product_id') ? $request->get('product_id') : null;
                $cae->product_name = $request->has('product_name') ? $request->get('product_name') : null;
                $cae->duration = $request->has('duration_year') && $request->has('duration_month') ? $request->get('duration_month').'|'.$request->get('duration_year') : null;
                if(empty($cae->unique_id_number)) {
                    $cae->unique_id_number = $request->has('unique_id_number') ? $request->get('unique_id_number') : null;
                }

                if($request->has('inverter') || $request->has('panel')){
                    if($request->get('inverter') == 'other'){
                        $inverterName = $request->get('other_inverter');
                    }else{
                        $inverterName = $request->get('inverter');
                    }
                    $cae->inverter = $inverterName;

                    if($request->get('panel') == 'other'){
                        $panelName = $request->get('other_panel');
                    }else{
                        $panelName = $request->get('panel');
                    }
                    $cae->panel = $panelName;

                    $cae->inverter_model_description = $request->has('model_description') ? $request->get('model_description') : null;
                    $cae->inverter_monthly_power_bill = $request->get('KW_installation');
                    $cae->inverter_KW_installation = $request->get('monthly_power_bill');
                    $cae->inverter_gross_project_amount = $request->get('gross_project_amount');
                    $cae->type_of_customer = $request->get('type_of_customer');
                    $cae->solar_power_type = $request->get('type_of_solar_power');
                    $cae->inverter_subsidy_amount = $request->get('subsidy_amount');
                    $cae->inverter_power_savings = $request->get('power_savings');
                }
                $cae->save();
            }


            $user = \App\User::find($consumer_application->user_id);
            if ($user) {
                $user->fill($request->input());
                $user->save();
            }

            $consumer_application->fill($request->input());

            if ($request->has('is_permanent_address') && $request->input('is_permanent_address') == 'yes') {
                $consumer_application->permanent_address_line_1   = $consumer_application->current_address_line_1;
                $consumer_application->permanent_address_state    = $consumer_application->current_address_state;
                $consumer_application->permanent_address_city     = $consumer_application->current_address_city;
                $consumer_application->permanent_address_pincode  = $consumer_application->current_address_pincode;
                $consumer_application->permanent_address_landmark = $consumer_application->current_address_landmark;
                $consumer_application->permanent_address_status   = $consumer_application->current_address_status;
            }

            if ($request->has('aadhaar_card') && $request->input('aadhaar_card')) {
                $aadhaar_card                       = str_replace(" ", "", $request->input('aadhaar_card'));
                $aadhaar_card                       = substr_replace($aadhaar_card, 'XXXX', 4, 4);
                $consumer_application->aadhaar_card = $aadhaar_card;
            }

            if ($request->has('co_applicant_day') && $request->input('co_applicant_day') && $request->input('co_applicant_month') && $request->input('co_applicant_year')) {
                $date_obj = date_parse_from_format('d-m-Y', $request->input('co_applicant_day') . '-' . $request->input('co_applicant_month') . '-' . $request->input('co_applicant_year'));
                if (is_array($date_obj)) {
                    $consumer_application->co_applicant_dob = $date_obj['year'] . '-' . $date_obj['month'] . '-' . $date_obj['day'];
                }
            }

            if ($request->has('day') && $request->input('day') && $request->input('month') && $request->input('year')) {
                $date_obj = date_parse_from_format('d-m-Y', $request->input('day') . '-' . $request->input('month') . '-' . $request->input('year'));
                if (is_array($date_obj)) {
                    $consumer_application->dob = $date_obj['year'] . '-' . $date_obj['month'] . '-' . $date_obj['day'];
                }
            }

            if ($request->has('experience_year') && $request->input('experience_year') && $request->input('experience_month')) {
                $consumer_application->experience = ($request->input('experience_year') * 12) + $request->input('experience_month');
            }

            $consumer_application->completed_stage = $request->input('current_stage');
            $consumer_application->updated_by      = $request->has('api_init') ? 'website-api' : 'website';

            //Co applicant logic
            $data = array();
            if ($request->input('current_stage') == 2) {
                $data['employee_status'] = $consumer_application->employee_status;

                $consumer_application->co_applicant_required = 0;
                $data['co_applicant']                        = false;

                if($consumer_application->merchant_id !== 6543) {
                    //amount > 1 lakhs
                    if ($consumer_application->loan_amount > 100000) {
                        $data['co_applicant'] = true;
                        $consumer_application->co_applicant_required = 1;
                    }

                    //property is rented
                    if ($consumer_application->current_address_status == 'RENTED') {
                        $data['co_applicant'] = true;
                        $consumer_application->co_applicant_required = 1;
                    }

                    //age not between 23-50
                    $dateOfBirth = $consumer_application->dob;
                    $today = date("Y-m-d");
                    $diff = date_diff(date_create($dateOfBirth), date_create($today));
                    $age = $diff->format('%y');
                    if ($age < 23 || $age > 50) {
                        $data['co_applicant'] = true;
                        $consumer_application->co_applicant_required = 1;
                    }

                    //unemployed
                    if ($consumer_application->employee_status == 'UNEMPLOYED') {
                        $data['co_applicant'] = true;
                        $consumer_application->co_applicant_required = 1;
                    }

                    //monthlty income less than 20000
                    if ($consumer_application->monthly_income < 20000) {
                        $data['co_applicant'] = true;
                        $consumer_application->co_applicant_required = 1;
                    }
                }
            }

            /*Update File Upload & insert into ConsumerApplicationFiles*/
            if ($request->file_income_proof) {

                ConsumerApplicationFiles::where('consumer_application_id', $request->input('application_id'))->where('file_type', 'file_income_proof')->delete();

                foreach ($request->file_income_proof as $key => $file) {

                    if ($file) {
                        //\Cloudder::upload($file);
                        //$Cloudder = \Cloudder::getResult();
                        (new ConsumerApplicationController())->uploadSingleFile($request->input('application_id'), 'income_proof', $file, $request);
                        /*if (isset($Cloudder['url'])) {
                            $consumer_application_file                          = new ConsumerApplicationFiles();
                            $consumer_application_file->consumer_application_id = $request->input('application_id');
                            $consumer_application_file->file_type               = "income_proof";
                            $consumer_application_file->file_path               = $Cloudder['secure_url'];
                            $consumer_application_file->save();
                        }*/
                    }
                }
            }

            if ($request->file_bank_statement) {

                ConsumerApplicationFiles::where('consumer_application_id', $request->input('application_id'))->where('file_type', 'file_bank_statement')->delete();

                foreach ($request->file_bank_statement as $key => $file) {

                    if ($file) {
                        //\Cloudder::upload($file);
                        //$Cloudder = \Cloudder::getResult();
                        (new ConsumerApplicationController())->uploadSingleFile($request->input('application_id'), 'bank_statement', $file, $request);
                        /*if (isset($Cloudder['url'])) {
                            $consumer_application_file                          = new ConsumerApplicationFiles();
                            $consumer_application_file->consumer_application_id = $request->input('application_id');
                            $consumer_application_file->file_type               = "bank_statement";
                            $consumer_application_file->file_path               = $Cloudder['secure_url'];
                            $consumer_application_file->save();
                        }*/
                    }

                }
            }

            if ($request->hasfile('file_pan_card')) {
                $file = $request->file('file_pan_card');
                (new ConsumerApplicationController())->uploadSingleFile($request->input('application_id'), 'file_pan_card', $file, $request);
                //\Cloudder::upload($file);
                //$Cloudder = \Cloudder::getResult();
                /*if (isset($Cloudder['url'])) {
                    $file_id = ConsumerApplicationFiles::where('consumer_application_id', $request->input('application_id'))->where('file_type', 'file_pan_card')->first();
                    if ($file_id) {
                        $consumer_application_file            = ConsumerApplicationFiles::find($file_id->id);
                        $consumer_application_file->file_path = $Cloudder['secure_url'];
                        $consumer_application_file->save();
                    } else {
                        $consumer_application_file                          = new ConsumerApplicationFiles();
                        $consumer_application_file->consumer_application_id =$request->input('application_id');
                        $consumer_application_file->file_type               = "pan_card";
                        $consumer_application_file->file_path               = $Cloudder['secure_url'];
                        $consumer_application_file->save();
                    }
                }*/
            }

            if ($request->hasfile('file_aadhaar_card')) {
                $file = $request->file('file_aadhaar_card');
                //\Cloudder::upload($file);
                //$Cloudder = \Cloudder::getResult();
                (new ConsumerApplicationController())->uploadSingleFile($request->input('application_id'), 'file_aadhaar_card', $file, $request);
                /*if (isset($Cloudder['url'])) {
                    $file_id = ConsumerApplicationFiles::where('consumer_application_id', $request->input('application_id'))->where('file_type', 'file_aadhaar_card')->first();
                    if ($file_id) {
                        $consumer_application_file            = ConsumerApplicationFiles::find($file_id->id);
                        $consumer_application_file->file_path = $Cloudder['secure_url'];
                        $consumer_application_file->save();
                    } else {
                        $consumer_application_file                          = new ConsumerApplicationFiles();
                        $consumer_application_file->consumer_application_id = $request->input('application_id');
                        $consumer_application_file->file_type               = "aadhar_card";
                        $consumer_application_file->file_path               = $Cloudder['secure_url'];
                        $consumer_application_file->save();
                    }
                }*/
            }
            if ($request->hasfile('file_aadhaar_card_back')) {
                $file = $request->file('file_aadhaar_card_back');
                //\Cloudder::upload($file);
                //$Cloudder = \Cloudder::getResult();
                (new ConsumerApplicationController())->uploadSingleFile($request->input('application_id'), 'file_aadhaar_card_back', $file, $request);
                /*if (isset($Cloudder['url'])) {
                    $file_id = ConsumerApplicationFiles::where('consumer_application_id', $request->input('application_id'))->where('file_type', 'file_aadhaar_card')->first();
                    if ($file_id) {
                        $consumer_application_file            = ConsumerApplicationFiles::find($file_id->id);
                        $consumer_application_file->file_path = $Cloudder['secure_url'];
                        $consumer_application_file->save();
                    } else {
                        $consumer_application_file                          = new ConsumerApplicationFiles();
                        $consumer_application_file->consumer_application_id = $request->input('application_id');
                        $consumer_application_file->file_type               = "aadhar_card";
                        $consumer_application_file->file_path               = $Cloudder['secure_url'];
                        $consumer_application_file->save();
                    }
                }*/
            }

            if ($request->hasfile('file_electricity_bill')) {
                $file = $request->file('file_electricity_bill');
                //\Cloudder::upload($file);
                //$Cloudder = \Cloudder::getResult();
                (new ConsumerApplicationController())->uploadSingleFile($request->input('application_id'), 'file_electricity_bill', $file, $request);
                /*if (isset($Cloudder['url'])) {
                    $file_id = ConsumerApplicationFiles::where('consumer_application_id', $request->input('application_id'))->where('file_type', 'file_electricity_bill')->first();
                    if ($file_id) {
                        $consumer_application_file            = ConsumerApplicationFiles::find($file_id->id);
                        $consumer_application_file->file_path = $Cloudder['secure_url'];
                        $consumer_application_file->save();
                    } else {
                        $consumer_application_file                          = new ConsumerApplicationFiles();
                        $consumer_application_file->consumer_application_id = $request->input('application_id');
                        $consumer_application_file->file_type               = "electricity_bill";
                        $consumer_application_file->file_path               = $Cloudder['secure_url'];
                        $consumer_application_file->save();
                    }
                }*/
            }

            $consumer_application->save();

            //email & sms notify
            if (($request->input('current_stage') == 2 && !$consumer_application->co_applicant_required) || $request->input('current_stage') == 3) {

                $hashids   = new Hashids('Creditfair by CS', 20);
                try {
                    $bitly_url = Shortio::getUrl(asset('application/' . $hashids->encode($consumer_application->id) . '?docs=true'));
                }catch (\Exception $e){
                    $bitly_url = asset('application/' . $hashids->encode($consumer_application->id) . '?docs=true');
                }

                if (is_object($bitly_url)){
                    $bitly_url = asset('application/' . $hashids->encode($consumer_application->id) . '?docs=true');
                }

                //EMAIL notification
                $mail_data                  = $consumer_application->toArray();
                $mail_data['merchant_name'] = "Creditfair";

                if ($mail_data['merchant_id']) {
                    $merchant = \App\Merchant::find($mail_data['merchant_id']);
                    if ($merchant) {
                        $mail_data['merchant_name'] = $merchant->merchant_name;
                    }
                }

                if($mail_data['merchant_id'] != 6543) {
                    if ($mail_data['email']) {
                        \Mail::send(['html' => 'emails.customer-loan-apply'], $mail_data, function ($message) use ($mail_data) {
                            $message->to(wall_decrypt($mail_data['email']), $mail_data['name'])->subject
                            ('Thanks for applying to Credit Fair!');
                        });
                    }

                    /*if(_env('NOTIFY_EMAIL', ''))
                    {
                        \Mail::send('emails.customer-loan-admin-notification', $mail_data, function ($message) use ($mail_data) {
                            $message->to(_env('NOTIFY_EMAIL', ''), 'Credit Fair Support')->subject
                                ('[Credit Fair]New Application Completed by ' . $mail_data['name']);
                        });
                    }*/

                    //SMS notification
                    $message = "Dear " . $consumer_application->name . ", Thanks for applying to Credit Fair! We'e received your request for an easy EMI plan of Rs " . $consumer_application->loan_amount . ". To help us make a decision within 24 hours can you please share the additional documents at " . $bitly_url . ".  <br/>You can view your loan application status through our consumer application by login through below link https://bit.ly/3pkSXS6.<br/>Best Regards,<br/>Team Credit Fair";

                    $mobile_number = '91' . $consumer_application->mobile_number;
                    send_sms($mobile_number, ['message' => $message, 'id' => $request->input('application_id'), 'id_type' => 'application_id']);
                }
            }

            $data['status']  = 'success';
            $data['message'] = 'Application Submitted successfully';
            $data['hashId'] = $this->getApplicationNo($consumer_application->id);
            if(!isset($merchant) || !isset($merchant->id)){
                $merchant = Merchant::where('id', $consumer_application->merchant_id)->first(['id', 'pre_approval', 'is_auto_doc', 'is_auto_approve', 'grade_id']);
            }

            if($request->get('loan_amount')){
                $this->updateStatus($user->id, $consumer_application->id, 'in-process');
            }


            if(isset($merchant->id) && ($merchant->is_auto_approve || $merchant->is_auto_doc || $merchant->pre_approval) && $merchant->grade_id && $request->get('monthly_income') > 0) {
                $queue = QueueLog::where('input', 'like', '%'.$consumer_application->id.'%')->where('input', 'like', '%command:AutoDecision%')->first();
                if(!isset($queue->job_id)) {
                    event(new EventAutoDecision(['id' => $consumer_application->id]));
                }
            }
        } else {
            $data['status']  = 'failure';
            $data['message'] = 'Retry Application';
            $data['hashId'] = '';
        }
        return response()->json($data);
    }

    public function getApplicationNo($id){
        try {
            $application = ConsumerApplication::with('merchant')->where('id', $id)->first(['id', 'merchant_id']);
            $agreement_no = (new ConsumerApplicationController)->getLoanApplicationID($id, $application->merchant);
            $newProforma = new ProFormaInvoice();
            $newProforma->application_id = $id;
            $newProforma->loan_application_no = $agreement_no;
            $newProforma->save();
            return $agreement_no;
        }catch (\Exception $e){

        }
    }

    public function getAdditionalDocuments(Request $request)
    {
        if ($request->has('application_id')) {
            $consumer_application                       = \App\ConsumerApplication::find($request->input('application_id'));
            $consumer_application->additional_docs      = true;
            $consumer_application->additional_docs_list = implode(',', $request->input('additional_docs_list'));
            $consumer_application->save();

            $hashids   = new Hashids('Creditfair by CS', 20);
            try {
                $bitly_url = Shortio::getUrl(asset('application/' . $hashids->encode($consumer_application->id)));
            }catch (\Exception $e){
                $bitly_url = asset('application/' . $hashids->encode($consumer_application->id));
            }

            $message = "Thanks for applying to Credit Fair! Please upload the requested documents to " . $bitly_url . " and help us give you a quick decision.<br/>Best Regards,<br/>Team Credit Fair";

            $mobile_number = '91' . $consumer_application->mobile_number;
            send_sms($mobile_number, ['message'=>$message,'id'=>$request->input('application_id'),'id_type'=>'application_id']);

            $data['status']  = 'success';
            $data['message'] = 'Request Submited successfully';
        } else {
            $data['status']  = 'failure';
            $data['message'] = 'Retry Application';
        }
        return response()->json($data);
    }

    public function getMerchants($id){
        $data = Merchant::where('category_id',$id)->where('status','active')->where('is_guest_active',1)->get(['merchant_name as name','id']);

        $options = '<option value="">Name of Merchant *</option>';
        foreach($data as $item){
            $options .= "<option value=" . $item->id . ">" . $item->name . "</option>";
        }

        //$options .= "<option value='0'>Other</option>";

        return response()->json($options,200);
    }

    public function getCities($state_id){
        $data = CityModel::where('state_id',$state_id)->get(['name','id']);

        $options = '<option value="">Select City *</option>';
        foreach($data as $item){
            $options .= "<option value=" . $item->name . ">" . $item->name . "</option>";
        }

        return response()->json($options,200);
    }

    public function deleteComment(){
        $type = (Input::has('type')) ? Input::get('type') : 'consumer';
        $status = 'OK';
        $comments = Comments::with('user')->where('id',Input::get('c_id'))->where('type',$type)->delete();
        if(!$comments){
            $status = 'FAIL';
        }
        return response()->json(['status'=>$status],200);
    }

    public function getComments($application_id){

        $type = (Input::has('type')) ? Input::get('type') : 'consumer';
        $lender_id = (Input::has('lender_id')) ? Input::get('lender_id') : 0;
        //$application = ConsumerApplication::where('id', $application_id)->first(['state']);

        $comments = Comments::with('user')->where('application_id',"=",$application_id)->where('type',$type)->orderBy('created_at','desc');
        if(Auth::check() && Auth::user()->user_type == UserTypes::$merchant_v2){
            $comments = $comments->where('show_merchant','=',1);
        }
        if($lender_id){
            $comments = $comments->where('show_avanse', $lender_id);
        }
        $comments = $comments->get();
        $list = '';
        foreach ($comments as $comment){
            $visible = '';
            if ($comment->confidential_notes == 1) {
                $consumerApplicationController = new consumerApplicationController();
                $permissions_comments = $consumerApplicationController->checkPermissionGetComments();
                if($permissions_comments){
                    $visible = "Confidential Notes";
                } else {
                    continue;
                }
            } else {
                if ($comment->show_merchant == 1 && $comment->show_consumer == 1) {
                    $visible = "Visible to Merchant and Customer";
                } elseif ($comment->show_merchant == 1 && $comment->show_consumer == 0) {
                    $visible = "Visible to Merchant";
                } elseif ($comment->show_merchant == 0 && $comment->show_consumer == 1) {
                    $visible = "Visible to Customer";
                } elseif ($comment->show_merchant == 0 && $comment->show_consumer == 0 && $comment->show_avanse) {
                    $lender = Lenders::where('id', $comment->show_avanse)->first();
                    $visible = "Visible to " . $lender->name;
                }
            }
            $visible = (Auth::check() && Auth::user()->user_type == UserTypes::$merchant_v2) ? '' : $visible;
            $name = isset($comment->user->name) ? $comment->user->name : 'Credit Fair';
            $delete_comment = '';
            if(Input::has('id')) {
                //$user = User::find(Input::get('id'));
                if(Input::has('delete_merchant_comment') && Input::get('delete_merchant_comment') == 1 && ((!isset($comment->request_review) || (isset($comment->request_review) && $comment->request_review!=1 && $comment->request_review!=0) ))) {
                    $delete_comment = ' <i style="cursor:pointer;" data-id="' . $comment->id . '" class="delete-comment fa fa-trash"></i>';
                }
            }

            $avIcon = isset($comment->user->lender_id) && $comment->user->lender_id == AvanseServices::$lender_id ? '<img style="width: 14px;" src="/assets/front/img/avanse.png"/>' : (isset($comment->user->lender_id) && $comment->user->lender_id == Services::$lender_id ? '<img style="width: 14px;" src="/assets/front/img/abfl.jpeg"/>' : '');
            $list .= '<li><div>'.$avIcon.' '.ucfirst($name).'<span> '.date('d, F Y H:i:s',strtotime($comment->created_at)).'</span>'.$delete_comment.'</div><div>'.static::getPureComment(new Request(['comment' => self::replace_links_with_anchor($comment->comment)]))['comment'].'</div><div style="font-size: 10px;">'.$visible.'</div></li>';
        }
        return response()->json(['comments'=>$list],200);
    }

    public static function getPureComment(Request $request){
        $comments = explode(' ',($request->has('comment')) ? $request->get('comment') : Input::get('comment'));
        $pureComment = '';
        $users = [];
        foreach ($comments as $comment){
            if (strpos($comment, '@') !== false && strpos($comment, '-') !== false){
                $user_id = (int) filter_var($comment, FILTER_SANITIZE_NUMBER_INT);
                $users[] = $user_id;
                $pureComment .= ' '.str_replace('@'.$user_id.'-','',$comment);
            }else{
                $pureComment .= ' '.$comment;
            }
        }

        return ['comment' => $pureComment, 'users' => $users, 'original_comment' => ($request->has('comment')) ? $request->get('comment') : Input::get('comment')];
    }

    public static function replace_links_with_anchor($text) {

        if (!$text)
            return $text;

        return preg_replace_callback(
            '/\bhttps?:\/\/[^\s]+/i', // Regex to match URLs
            function ($matches) {
                $url = str_replace("&amp;", "&", $matches[0]);
                return '<a href="' . htmlspecialchars($url) . '" target="_blank">View Link</a>';
            },
            $text
        );
    }

    public function getMerchantOffers(Request $request){
        setlocale(LC_MONETARY, 'en_IN.UTF-8');
        if ($request->has('id')){
            $merchant = Merchant::find($request->get('id'));
            if (isset($merchant->id)) {
                $request->attributes->add(['merchant_id' => $request->get('id'), 'loan_amount' => $request->get('loan_amount'), 'category_id' => $merchant->category_id,'application_id' => 0]);
                $calculation = new EMICalculation($request);
                $newOfferData = $calculation->prepareCalculation()->getData();
                $html = "<div style='padding-bottom: 14px;'>Loan Amount: &#x20B9;".$request->get('loan_amount')."</div><table class='table table-hover'><tr><th>Choose EMI</th><th>Total EMI</th><th>Advance EMI</th><th>EMI Amount</th><th>Interest Rate</th><th>DownPayment</th><th>Processing Fee</th></tr>";
                foreach ($newOfferData as $offer){
                    $checkced = '';
                    if ($request->get('appended_offer_id') == $offer->id){
                        $checkced = 'checked="checked"';
                    }
                    $html .= '<tr class="choose-emi-plan" data-tenure="'.$offer->total_emi.'" data-offer-id="'.$offer->id.'"><td><input style="outline: none;left: 0;visibility: visible !important; position: relative !important;" type="radio" name="offer_id" '.$checkced.' value="'.$offer->id.'"/></td><td>'.$offer->total_emi.'</td><td>'.$offer->payable_in_advanced.'</td><td>&#x20B9;'.str_replace('.00','',money_format('%!i',$offer->emi)).'</td><td>'.$offer->flat_annual_interest.'%</td><td>&#x20B9;'.str_replace('.00','',money_format('%!i',$offer->up_front_from_customer)).'</td><td>&#x20B9;'.str_replace('.00','',money_format('%!i',$offer->processing_fee)).'</td></tr>';
                }

                $html .= '</table>';

                return response()->json(['status' => 'OK','data' => $html], 200);
            }
        }
        return response()->json(['status' => 'FAIL'], 200);
    }

    public function getMerchantCentres(Request $request){
        setlocale(LC_MONETARY, 'en_IN.UTF-8');
        if ($request->has('id')){
            if ($request->get('id')) {
                $centres = MerchantLocation::where('merchant_id', $request->get('id'))->whereNull('deleted_at')->select('id', 'name', 'merchant_id')->orderBy('name', 'asc')->get();
                $html = '<option value="">Name of Center <span class="required">*</span></option>';
                foreach ($centres as $centre){
                    $html .= '<option value="'.$centre->id.'">'.ucfirst($centre->name).'</option>';
                }

                return response()->json(['status' => 'OK','data' => $html], 200);
            }
        }
        return response()->json(['status' => 'FAIL'], 200);
    }

    public function updateComments(Request $request, $saveMandatoryCall=0){
        $comments = '';
        $message = '';
        $reminder = false;
        try {

            if (Input::has('lender_id') && Input::get('lender_id') > 0 && Input::has('isAppID')){
                ConsumerApplication::where('id', Input::get('application_id'))->update(['lender_id' => Input::get('lender_id')]);
            }

            $bool =  Input::get('advance_payment_receipt');
            if($bool == 'true' || $bool == 'false'){
                $advance_payment_receipt = $bool == 'true' ? 1 : 0;
            }

            if (Input::has('advance_payment_receipt')){
                ConsumerApplicationElement::where('application_id', Input::get('application_id'))->update(['advance_payment_verified' => $advance_payment_receipt]);
            } 

            if(Input::has('comment') && !empty(Input::get('comment'))) {

                $getComment = static::getPureComment(new Request());

                $pureComment = html_entity_decode($getComment['comment'], ENT_QUOTES);
                $cleanOriginalComment = html_entity_decode($getComment['original_comment'], ENT_QUOTES);

                $visible = '';
                $comment = new Comments();
                $comment->application_id = Input::get('application_id');
                $comment->user_id = Input::get('id');
                $comment->comment = $cleanOriginalComment;
                if(Input::has('type') && (Input::get('type') == 'merchant' || Input::get('type') == 'lead') || Input::get('type') == 'pr_lead'){
                    $comment->type = Input::get('type');
                }

                $whom_to = Input::has('whom_to') ? Input::get('whom_to') : '';
                if($whom_to) {
                    $whom_to = array_values($whom_to);
                    $whom_to = implode('|', $whom_to);
                }
                $date_reminder = Input::has('date_reminder') ? Input::get('date_reminder') : '';

                if($whom_to && $date_reminder) {
                    $comment->date_reminder = Input::has('date_reminder') ? Input::get('date_reminder') : '';
                    $comment->whom_to = $whom_to;
                    $comment->whatsapp = (Input::get('whatsapp')) ? 1 : 0;
                    $comment->sms = (Input::get('sms')) ? 1 : 0;
                    $comment->email = (Input::get('email')) ? 1 : 0;
                    $comment->slack = (Input::get('slack')) ? 1 : 0;
                    $reminder = true;
                }

                $comment->show_merchant = (Input::get('show_merchant')) ? 1 : 0;
                $comment->show_consumer = (Input::get('show_consumer')) ? 1 : 0;
                $comment->confidential_notes = (Input::get('confidential_notes')) ? 1 : 0;

                if(Input::get('request_review') == 1){
                    $comment->request_review = 1;
                }
                if(Input::get('approval_request_review') == 1){
                    $comment->approval_request_review = 1;
                }

                if(Input::get('confidential_notes') == 1){
                    $comment->confidential_notes = 1;
                }

                $username = User::where('id', Input::get('id'))->first(['name','lender_id']);

                $comment->show_avanse = (Input::get('show_avanse')) ? Input::get('show_avanse') : (isset($username->lender_id) && $username->lender_id == AvanseServices::$lender_id ? $username->lender_id : 0);

                $comment->save();
                if($comment->show_merchant == 1 && $comment->show_consumer == 1){
                    $visible = "Visible to Merchant and Customer";
                }elseif($comment->show_merchant == 1 && $comment->show_consumer == 0){
                    $visible = "Visible to Merchant";
                }elseif($comment->show_merchant == 0 && $comment->show_consumer == 1){
                    $visible = "Visible to Customer";
                }elseif($comment->show_merchant == 0 && $comment->show_consumer == 0 && $comment->show_avanse){
                    $lender = Lenders::where('id', $comment->show_avanse)->first();
                    $visible = "Visible to ".$lender->name;
                }elseif($comment->confidential_notes == 1){
                    $visible = "Confidential Notes";
                    }

                if($comment->show_merchant){
                    $applicationController = new ConsumerApplicationController();
                    $status = 'Merchant-Comment';
                    $consumerApplication = ConsumerApplication::where('id', $comment->application_id)->first(['merchant_id']);
                    if(isset($consumerApplication->merchant_id)) {
                        $applicationController->webhook($comment->application_id, ['merchant_id' => $consumerApplication->merchant_id, 'type' => 'Application-Webhook', 'status' => $status, 'data' => $applicationController->getMConnectPayload($comment->application_id, $status, ['comment' => $comment->comment])]);
                    }
                }

                if (_env('WHATSAPP_STATUS_AND_COMMENT') && ($comment->show_merchant == 1 || $comment->type == 'merchant')) {
                    try {
                        (new ServiceController(new Request()))->sendGroupCommentNotification(
                            $comment->application_id,
                            $cleanOriginalComment,
                            $username->name
                        );
                    } catch (\Exception $_e) {
                        // non-blocking — existing flow continues
                    }
                }

                $message = 'Application updated successfully!';

                $delete_comment = '';
                if(Input::has('id')) {
                    $user = User::find(Input::get('id'));
                    if(Session::has('delete_merchant_comment|-1')) {
                        $delete_comment = ' <i style="cursor:pointer;" data-id="' . $comment->id . '" class="delete-comment fa fa-trash"></i>';
                    }
                }

                $comments .= '<li><div>' . ucfirst($username->name) . '<span> ' . date('d, F Y H:i:s') . '</span>'.$delete_comment.'</div><div>' . self::replace_links_with_anchor($pureComment) . '</div><div style="font-size: 10px;">'.$visible.'</div></li>';

                if (Input::get('show_merchant')) {
                    $this->postCommentNotification(Input::get('application_id'), $pureComment);
                    $merchant = Merchant::where('id',Input::get('application_id'))->first(['contact_number','rcp_mobile']);
                    if (isset($merchant->contact_number) && !empty($merchant->contact_number)) {
                        $m_phone = $merchant->contact_number;
                        send_sms($m_phone, $pureComment);
                    }
                    if (isset($merchant->rcp_mobile) && !empty($merchant->rcp_mobile) && (!isset($m_phone) || (isset($m_phone) && $m_phone != $merchant->rcp_mobile))) {
                        send_sms($merchant->rcp_mobile, $pureComment);
                    }
                }

                if(!$reminder) {

                    if ($getComment['users']/* && (!Input::has('type') || (Input::has('type') && Input::get('type') != 'merchant'))*/) {
                        $usersContacts = User::whereIn('id', $getComment['users'])->get(['mobile_number','email']);
                        $merchantName = '';
                        if ($comment->type == 'merchant'){
                            $application = Merchant::where('id', Input::get('application_id'))->first(['id', 'merchant_name as name', 'contact_number']);
                        }else if ($comment->type == 'lead'){
                            $application = Leads::where('id', Input::get('application_id'))->first(['id', 'firm as name']);
                            Leads::where('id', Input::get('application_id'))->update(['updated_at' => Carbon::now()->toDateTimeString()]);
                        }else if ($comment->type == 'pr_lead'){
                            $application = ProjectLeads::where('id', Input::get('application_id'))->first(['id', 'firm as name']);
                        }else{
                            $application = ConsumerApplication::with('merchant')->where('id', Input::get('application_id'))->first(['id', 'name', 'merchant_id', 'mobile_number']);
                            if(isset($application->merchant)){
                                $merchantName = $application->merchant->merchant_name;
                            }
                        }

                        $commenter = isset($user) && isset($user->name) ? $user->name : '';

                        if (empty($commenter)) {
                            if (Input::has('id')) {
                                $user = User::find(Input::get('id'));
                                $commenter = isset($user) && isset($user->name) ? $user->name : '';
                            }
                        }

                        $entity = [];
                        if($comment->type == 'merchant'){
                            $link = "<a href='https://creditfair.in/admin/merchant/edit/$application->id'>Click Here</a>";
                            $pureCommentNew = "Merchant Name: $application->name\nCommented By: $commenter\nApplication Link: $link\n$pureComment";
                        }elseif($comment->type == 'lead'){
                            $link = "<a href='https://creditfair.in/admin/lead/$application->id'>Click Here</a>";
                            $pureCommentNew = "Lead Name: $application->name\nCommented By: $commenter\nLead Link: $link\n$pureComment";
                        }elseif($comment->type == 'pr_lead'){
                            $link = "<a href='https://creditfair.in/admin/project-lead/$application->id'>Click Here</a>";
                            $pureCommentNew = "Lead Name: $application->name\nCommented By: $commenter\nLead Link: $link\n$pureComment";
                        }else{
                            $link = "<a href='https://creditfair.in/admin/consumer-applications/edit/$application->id'>Click Here</a>";
                            $pureCommentNew = "Customer Name: $application->name\nMerchant Name: $merchantName\nCommented By: $commenter\nApplication Link: $link\n$pureComment";
                            // $entity = ['templateid' => '1307161742932102559', 'entityid' => Templates::$entityid];
                        }

                        if (Input::has('mandatory_document_list') && Input::get('mandatory_document_list') && Input::get('application_id')){
                            $mandatory_docs = ConsumerApplicationElement::where('application_id', Input::get('application_id'))->first(['mandatory_document_list']);

                            $document_list = !empty($mandatory_docs->mandatory_document_list) ? $mandatory_docs->mandatory_document_list . ',' . Input::get('mandatory_document_list') : Input::get('mandatory_document_list');
                            $list_to_array = explode(',', $document_list);
                            $mandatory_lists = array_unique($list_to_array);

                            // Mapping of values to labels
                            $document_labels = [
                                'pan_card' => 'Pan card',
                                'aadhar_card' => 'Aadhaar card',
                                '6_month_bank_statement' => 'Latest 6 months bank statement',
                                '3_month_salary_slip' => 'Latest 3 months salary slip',
                                'offer_letter_with_joining_proof' => 'Offer Letter with joining proof',
                                'business_proof' => 'Business Proof (Shoptact, GST or Udhyog adhar)',
                                'income_proof' => 'Income proof (Salary slip, ITR, Form-16)',
                                'personal_discussion' => 'Personal Discussion',
                                'gst_returns' => 'GST returns',
                                'co_app_with_income' => 'Co-app with income',
                                'co_app_for_signing' => 'Co-app for signing',
                                'electricity_bill_own_house_proof' => 'Electricity Bill/Own house proof',
                                'atta_chakki' => 'Credit approved video (atta chakki)',
                                '12_month_bank_statement' => 'Latest 12 months bank statement (Current, OD)',
                                'audited_bs_pl_ac_with_schedule' => 'Audited B/S & P/L a/c with Schedules',
                                '2_year_itr_with_computation' => '2 years ITR with Computation',
                                'incorporation_certificate' => 'Incorporation Certificate',
                                'moa_aoa_lod_los' => 'MOA/AOA/LOD/LOS',
                                'quotation' => 'Quotation',
                                'entity_bureau' => 'Entity Bureau',
                                'directors_bureau' => 'Directors Bureau',
                                'noc_repayment_proof' => 'NOC/Repayment Proof',
                                'Other' => 'Other',
                            ];


                            if ($mandatory_lists) {
                                foreach ($mandatory_lists as $_list) {
                                    // Check if the document label exists in the array
                                    if (isset($document_labels[$_list])) {
                                        // Append the label to the pureCommentNew
                                        $pureCommentNew .= "\n\n" . $document_labels[$_list];
                                    } else {
                                        // If the value is not found in the mapping, append the original value
                                        $pureCommentNew .= "\n\n" . $_list;
                                    }
                                }
                            }
                        }
                        foreach ($usersContacts as $contact) {
                            if ($contact->email) {
                                $this->sendMessageOnMail($contact, $pureCommentNew, $commenter, $application->name, $application->id);
                            }
                        }
                    }
                }else{
                    $payload = [
                        'payload' => json_encode(['comment_id' => $comment->id, 'auth_user_id' => Input::get('id'), 'manual_reminder' => true]),
                        'from' => 'app_reminder',
                        'application_id' => Input::get('application_id'),
                        'available_at' => Carbon::parse($date_reminder)->toDateTimeString(),
                        'created_at' => Carbon::now()->toDateTimeString()
                    ];
                    JobProvider::insert($payload);
                }

                if (Input::has('av_cancelled') && Input::get('av_cancelled')){
                    $applicationData = ConsumerApplication::where('id', Input::get('application_id'))->update(['lender_id' => 2]);
                    (new Slack(new Request(['title' => 'Application is rejected by Avanse', 'fields' => ['Name' => $applicationData->name, 'Message' => $getComment['original_comment'], 'application_id' => $applicationData->id], 'group' => Slack::$CASE_REVIEWS])))->send();
                }
            }

            $co_applicant_signing = (Input::get('co_applicant_signing')) ? 1 : 0;
            $co_applicant_income = (Input::get('co_applicant_income')) ? 1 : 0;

            if ($co_applicant_income) {
                $reasons[] = 'income';
            }

            if ($co_applicant_signing) {
                $reasons[] = 'signing';
            }

            if ($co_applicant_signing || $co_applicant_income) {
                $consumerApplication = ConsumerApplication::where('id', Input::get('application_id'))->first(['merchant_id']);
                ConsumerApplicationElement::where('application_id', Input::get('application_id'))->update([
                    'co_applicant_for_signing' => $co_applicant_signing,
                    'co_applicant_for_income' => $co_applicant_income,
                ]); 
            $autodecisionCheckresponse = (new autoBRE())->checkAutoBREStatus(Input::get('application_id'));
            $autoBREStatus = isset($autodecisionCheckresponse->getData()->status)? $autodecisionCheckresponse->getData()->status: '';

            if ($autoBREStatus !== 'FAIL') {           
                $webhookStatus = 'Add-Co-applicant';
                $reasonString = 'Co-applicant needed for ' . implode(' & ', $reasons);
                $addn_data = ['user_id' => Input::get('auth_user_id'), 'reason' => $reasonString];

                $consumerController = new ConsumerApplicationController();
                $consumerController->webhook(Input::get('application_id'), [
                    'merchant_id' => $consumerApplication->merchant_id,
                    'type' => 'Application-Webhook',
                    'status' => $webhookStatus,
                    'data' => $consumerController->getMConnectPayload(Input::get('application_id'), $webhookStatus, $addn_data)
                ]);
            }
        }

        if (Input::has('mandatory_document_list') && Input::get('mandatory_document_list') && Input::get('application_id')){
            $mandatory_docs = ConsumerApplicationElement::where('application_id',Input::get('application_id'))->first(['mandatory_document_list']);

            $document_list = !empty($mandatory_docs->mandatory_document_list) ? $mandatory_docs->mandatory_document_list .','. Input::get('mandatory_document_list') : Input::get('mandatory_document_list');
            $list_to_array=explode(',',$document_list);
            $mandatory_lists = array_unique($list_to_array);
            if($mandatory_lists) {
                // Create a formatted comment string
                $pureCommentDocuments = "Mandatory documents updated: ";
                if ($mandatory_lists) {
                    $pureCommentDocuments .= implode(', ', $mandatory_lists);
                }
            }
            // block to add comment with mail notification to advisor on mandatory document selection by credit team
            if(Input::has('id')) {
                $advisor_id = Input::get('advisor_id');
                if (!empty($advisor_id)) { // condition to added to fix the mandatory document selection on status change to approved
                    $user = User::where('id', Input::get('advisor_id'))->first(['id','mobile_number','email', 'name']);
                    $commenter = Auth::user()->name;
                    $pureCommentDocuments = '@'.$user->id.'-'.$user->name.' '.$pureCommentDocuments;
                    $this->sendMessageOnMail($user, $pureCommentDocuments, $commenter, Input::get('application_name'), Input::get('application_id'));
                }
            }

            $c[] = [
                'application_id' => (Input::get('application_id')) ? Input::get('application_id') : 0,
                'user_id' => isset(Auth::user()->id) ? Auth::user()->id : 107,
                'comment' => $pureCommentDocuments,
                'type' => "consumer",
                'show_merchant' => (Input::get('show_merchant')) ? 1 : 0,
                'show_consumer' => (Input::get('show_consumer')) ? 1 : 0,
                'created_at' => Carbon::now()->toDateTimeString(),
                'updated_at' => Carbon::now()->toDateTimeString(),
            ];
            if (isset($c)) {
                Comments::insert($c);
            }
            if(!isset($mandatory_lists)) {
                $mandatory_docs = ConsumerApplicationElement::where('application_id', Input::get('application_id'))->first(['mandatory_document_list']);

                $document_list = !empty($mandatory_docs->mandatory_document_list) ? $mandatory_docs->mandatory_document_list . ',' . Input::get('mandatory_document_list') : Input::get('mandatory_document_list');
                $list_to_array = explode(',', $document_list);
                $mandatory_lists = array_unique($list_to_array);
            }
            if (!in_array('co_app_for_signing',$mandatory_lists) && !in_array('co_app_with_income',$mandatory_lists) && !$saveMandatoryCall) {
                // Removed database update to avoid duplication with saveMandatoryDocument
                ConsumerApplicationElement::where('application_id',Input::get('application_id'))->update([
                    'mandatory_document_list' => implode(',',$mandatory_lists),
                ]);
            }

            MandatoryDocumentListLogs::insert([
                'application_id' => Input::get('application_id'),
                'user_id' => Input::has('id') ? Input::get('id') : 0,
                'mandatory_document_list' =>  Input::get('mandatory_document_list'),
                'created_at' => Carbon::now()->toDateTimeString()
            ]);


            $listOfDocuments = explode(',', Input::get('mandatory_document_list'));

            $list = "";
            foreach ($listOfDocuments as $index => $document) {
                $list .= ($index + 1) . ') ' . ucwords(str_replace('_', ' ', $document));
            }

            if (!isset($application)) {
                $application = ConsumerApplication::with('merchant')->where('id', Input::get('application_id'))->first(['name', 'merchant_id', 'mobile_number']);
            }

            $consumer_app_link = 'https://bit.ly/2HQO1EX';//\Bitly::getUrl('https://play.google.com/store/apps/details?id=com.consumer.creditfair&hl=en_US');
            $SMSMessage = "\nCongrats on being approved by Credit Fair! Please provide us with the following documents at the earliest. Download our consumer app to upload pending documents \n" . $consumer_app_link;

            $entity = ['templateid' => '1307159964302739126', 'entityid' => Templates::$entityid];
            //send_sms($application->mobile_number, ['message' => 'Dear ' . $application->name . ',' . $SMSMessage, 'id' => Input::get('application_id'), 'id_type'=> 'application_id',  'templateId' => Templates::$approved_c1, 'args' => [$application->name], 'templateDetails' => $entity]);
            if ($application->merchant) {

                $mSMSMessage = "\nCongrats! ".$application->name." got approved. Please provide us with the following documents at the earliest:\n".$list;

                $message = "Dear " . $application->merchant->merchant_name . ",<br>Congrats! ".$application->name." got approved. Please provide us with the following documents at the earliest:<br>".$list;
                $entity = ['templateid' => '1307159964354208939', 'entityid' => Templates::$entityid];
                $args = [$application->merchant->merchant_name, $application->name, $list];
            }
        }

        if (Input::has('query_reasons_slice') && Input::get('query_reasons_slice') && Input::get('application_id')){
            $disb_query_reasons = ConsumerApplicationElement::where('application_id',Input::get('application_id'))->first(['disb_query_reasons']);

            $disb_query_list = !empty($disb_query_reasons->disb_query_reasons) ? $disb_query_reasons->disb_query_reasons .','. Input::get('query_reasons_slice') : Input::get('query_reasons_slice');
            $disb_list_to_array=explode(',',$disb_query_list);
            $disb_mandatory_lists = array_unique($disb_list_to_array);
            ConsumerApplicationElement::where('application_id',Input::get('application_id'))->update([
                'disb_query_reasons' => implode(',',$disb_mandatory_lists),
            ]);
        }

    } catch (\Exception $e){
        $message = 'Exception occurred while updating comments';
    }

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

    public function sendMessageOnMail($user, $messaeg, $commenter, $name, $id){

        $message = str_replace("\n", "<br/>",$messaeg);

        Mail::send('emails.reminders.basic_reminder',
            ['body'=> $message]
            , function ($message) use ($user, $commenter, $name, $id) {
                $message->to($user->email)->subject('Tagged: '.ucwords($commenter).' tagged you on '.$id.' - '.ucwords($name).'\'s application');
        });
    }

    public function appReminder($job, $payload){
        if (isset($payload->comment_id) && $payload->comment_id > 0){
            $comment = Comments::find($payload->comment_id);
            if ($comment->whom_to) {
                $users = explode('|',$comment->whom_to);
                if ($users && (!Input::has('type'))) {
                    $usersContacts = User::whereIn('id', $users)->get(['id','mobile_number','email','slack_url']);

                    if ($comment->type == 'merchant'){
                        $application = Merchant::where('id', $job->application_id)->first(['id', 'merchant_name as name', 'contact_number']);
                    }else if ($comment->type == 'lead'){
                        $application = Leads::where('id', $job->application_id)->first(['id', 'firm as name']);
                        Leads::where('id', $job->application_id)->update(['updated_at' => Carbon::now()->toDateTimeString()]);
                    }else{
                        $application = ConsumerApplication::with('merchant')->where('id', $job->application_id)->first(['id', 'name', 'merchant_id', 'mobile_number']);
                    }

                    if (isset($payload->auth_user_id)) {
                        $user = User::find($payload->auth_user_id);
                        $commenter = isset($user) && isset($user->name) ? $user->name : '';
                    }

                    $getComment = static::getPureComment(new Request(['comment' => $comment->comment]));

                    $pureComment = $getComment['comment'];

                    if($comment->type == 'merchant'){
                        $link = "https://creditfair.in/admin/merchant/edit/" . $application->id;
                        $pureCommentNew = "Merchant Name: $application->name\nCommented By: $commenter\nApplication Link: $link\n$pureComment";
                    }elseif($comment->type == 'lead'){
                        $link = "https://creditfair.in/admin/lead/" . $application->id;
                        $pureCommentNew = "Lead Name: $application->name\nCommented By: $commenter\nLead Link: $link\n$pureComment";
                    }else{
                        $link = "https://creditfair.in/admin/consumer-applications/edit/" . $application->id;
                        $pureCommentNew = "Customer Name: $application->name\nCommented By: $commenter\nApplication Link: $link\n$pureComment";
                    }
                    foreach ($usersContacts as $contact) {
                        if ($comment->whatsapp && !$comment->sms) {
                            sendWhatsAppMessage($contact->mobile_number, $pureCommentNew);
                        }
                        if ($comment->sms) {
                            send_sms($contact->mobile_number, $pureCommentNew);
                        }
                        if ($comment->email){
                            $mail_message = $pureCommentNew;
                            $email_id = $contact->email;
                            Mail::send('emails.reminders.basic_reminder',
                                ['body'=> $mail_message], function ($mail_message) use ($email_id) {
                                    $mail_message->to($email_id)->subject('Check what reminder set for you');
                                });
                        }
                        if ($comment->slack){
                            (new Slack(new Request(['title' => 'Check what reminder set for you today', 'fields' => ['Reminder' => $pureCommentNew], 'group' => $contact->slack_url])))->send();
                        }
                    }
                }
            }
        }else if (isset($job->application_id)){
            $application = ConsumerApplication::with('comment','totalCalls','merchant', 'advisor')->where('id', $job->application_id)->whereNull('is_deleted')->whereNotIn('state',['aborted','rejected','nach registered','closed'])->first(['id', 'name', 'merchant_id', 'mobile_number','updated_by','created_by']);

            if ($application && !count($application->comment) && !count($application->totalCalls) && $application->merchant){
                $message = "No action is taken on ".$application->name."'s case from ".$application->merchant->merchant_name.", Kindly call and update the case status "."https://creditfair.in/admin/consumer-applications/edit/".$application->id;
                // $channel = "https://hooks.slack.com/services/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"; // for testing
                $channel = $application->updated_by == 'consumer_app' ? Slack::$APPLICATIONS_THROUGH_CONSUMER_APP : 'loan_application';
                $advisor_id = isset($application->advisor) && isset($application->advisor->id) ? $application->advisor->id : '';
                $slack_url = isset($application->advisor) && isset($application->advisor->slack_url) ? $application->advisor->slack_url : '';
                (new Slack(new Request(['title' => 'No-follow up. it\'s been more the 2 days', 'fields' => ['Name' => $application->name, 'Current Status' => $application->state, 'Message' => $message, 'application_id' => $application->id], 'tagging' => [$advisor_id], 'group' => $channel])))->send();
                (new Slack(new Request(['title' => 'No-follow up. it\'s been more the 2 days', 'fields' => ['Name' => $application->name, 'Current Status' => $application->state, 'Message' => $message, 'application_id' => $application->id], 'group' => $slack_url])))->send();
                $applicationController = new ConsumerApplicationController();
                $applicationController->updateSystemReminders($job->application_id);
            }
        }
    }

    public function postCommentNotification($id, $comment){
        $application = ConsumerApplication::find($id);
        if(isset($application->merchant_id)) {
            $request = [
                'type' => 'merchant',
                'id' => $application->merchant_id,
                'notification_type' => 'merchant_comment',
                'title' => 'Application Update - '.$application->name,
                'body' => $comment,
                'deeplink' => '/edit-application/' . $id . '?click=view_comments&highlight=true'
            ];
            new FCMNotification(new Request($request));
        }
    }


    public function postDocumentUpdateNotification($id, $message){
        $application = ConsumerApplication::find($id);
        if(isset($application->merchant_id)) {
            $request = [
                'type' => 'merchant',
                'id' => $application->merchant_id,
                'notification_type' => 'customer_document_required',
                'title' => 'Application Update - '.$application->name,
                'body' => $message,
                'deeplink' => '/edit-application/' . $id
            ];
            new FCMNotification(new Request($request));
        }
    }

    public function getOldDataValues($data){

        $payload = http_build_query($data);

        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => 'http://equifax.local/',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => $payload,
            CURLOPT_HTTPHEADER => array(
                "Content-Type: application/x-www-form-urlencoded",
            ),
        ));

        $response = curl_exec($curl);
        $err = curl_error($curl);

        curl_close($curl);

        return json_decode($response);
    }

    public function getEquifaxData(){
        $file_name=base_path().'/storage/test.csv';

        $data = file($file_name);
        foreach ($data as $line){
            $lineArray[] = explode("\t", $line);

        }

        if($lineArray) {
            foreach ($lineArray as $line) {
                $myArray[] = explode(',', $line[0]);
            }
        }
        unset($myArray[0]);
        $myArray = array_values($myArray);
        foreach ($myArray as $key=>$item) {
            $year = substr($item[2], 4, 4);
            $day = substr($item[2], 0, 2);
            $month = substr($item[2], 2, 2);
            $data = array('application_id'=>$key,'purpose'=>'05','name'=>$item[0],'dob'=>$year.'-'.$month.'-'.$day,'pan_card'=>$item[4],'address'=>$item[6],'state'=>$item[7],'postal_code'=>$item[8],'mobile_number'=>$item[3]);
            $this->getOldDataValues($data);
        }
    }

    public function getHypothecationStatus(Request $request){
        //$this->initiateHypothecation(new Request(['id' => $request->get('id')]));
        return (new LoanHypothecation($request))->getStatus();
    }

    public function getVivritiUtkarshStatus(Request $request){
        $application = ConsumerApplication::with('application_element')->where('id', $request->get('id'))->first();
        $missingArray = [];
        $workAdd = isset($application->work_address_line_1) ? true : array_push($missingArray, "Applicant office address missing");
        if($application->purpose == _env('SOLAR_CATEGORY_ID')){
            $solarInstallationAdd = isset($application->application_element->installation_address_line_1) ? true : array_push($missingArray, "Solar installation address missing");
        }
        $maritalStatus = isset($application->work_address_line_1) ? true : array_push($missingArray, "Applicant Marital Status missing");
        $motherName=isset($application->application_element->mother_name) ? true : array_push($missingArray, "Applicant mother name missing");
        $educationLevel=isset($application->application_element->education_level) ? true : array_push($missingArray, "Applicant education level missing");
        $caste=isset($application->application_element->applicant_caste) ? true : array_push($missingArray, "Applicant caste missing");
        $loantype=isset($application->application_element->loan_type) ? true : array_push($missingArray, "Applicant loan type missing");
        $religion=isset($application->application_element->applicant_religion) ? true : array_push($missingArray, "Applicant Religion missing");
        if (count($missingArray) == 0){
            return response()->json(['status' => 'OK', 'message' => null], 200);
        }
        $body  = '<table style="font-family: sans-serif;" class="table">';
        $body .= '<tr><td colspan="2" style="text-align: center;font-weight: 700;">Missing Feilds</td></tr>';
        $hide = 0;
        foreach ($missingArray as $value) {
            $body .= '<tr><td colspan="2">'.$value.'</td></tr>';
        }

        $body .= '</table>';

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


    public function getLeegalityWebhook(Request $request){
        (new Slack(new Request(['title' => 'getLeegalityWebhook', 'fields' => ['data' => json_encode($request->all())], 'group' => Slack::$STAGE_TESTING])))->send();
        event(new EventHypothecation(['webhook' => true, 'data' => $request->all()]));
        return response()->json(['status' => 'OK'], 200);
    }

    public function canHypothecated($application_id){
        $query = DB::select('SELECT merchant.id FROM consumer_application LEFT JOIN merchant ON merchant.id = consumer_application.merchant_id LEFT JOIN lenders ON lenders.id = consumer_application.lender_id WHERE merchant.is_hypothecation_active = 1 AND lenders.is_hypothecation_active = 1 AND consumer_application.id = ' . $application_id);

        if (isset($query[0]->id)){
            return true;
        }
        return false;
    }

    public function hypothecationCallback(Request  $request){
       (new Slack(new Request(['title' => 'Hypothecation debug point no 1', 'fields' => ['req' => json_encode($request->all())], 'group' => Slack::$STAGE_TESTING])))->send();

        if ($request->get('documentId')){
            $loanHypothecationModel = LoanHypothecationModel::where('documentId', $request->get('documentId'))->whereNull('deleted_at')->orderBy('created_at', 'desc')->first(['application_id', 'id']);
            if(isset($loanHypothecationModel->application_id)){
                $loanHypothecation = new LoanHypothecation($request);
                $loanHypothecation->updateHypothecation($loanHypothecationModel->application_id, $loanHypothecationModel->id);
                $hashids = new Hashids('Creditfair by CS', 20);
                $hashed_id = $hashids->encode($loanHypothecationModel->application_id);
                return \redirect()->to(asset('esign/'.$hashed_id.'?documentId='.$request->get('documentId')));
            }
        }
        abort(404);
    }

    public function initiateHypothecation(Request $request){

//        (new Slack(new Request(['title' => 'Callback - Leegality - 10', 'fields' => ['req' => json_encode($request->all())], 'group' => Slack::$STAGE_TESTING])))->send();
        if (!$this->canHypothecated($request->get('id'))){
            return response()->json(['status' => 'FAIL'], 400);
        }

        if($request->has('documentId') && $request->get('documentId')){

            if(_env('DIGIO_SIGNING') == 1) {
                $loanHypothecation = new DigioHypothecation($request);
            }else{
                $loanHypothecation = new LoanHypothecation($request);
            }

            if($loanHypothecation->updateHypothecation($request->get('id'))){
                return response()->json(['status' => 'FAIL', 'message' => 'Already initiated, returning to thank you page'], 200);
            }
        }

        if($request->has('re_trigger') && $request->get('re_trigger')){
            // Resend API notification via Digio (primary); fall back to Leegality on failure
            try {
                if(_env('DIGIO_SIGNING') == 1) {
                    (new DigioHypothecation($request))->resendNotification();
                    (new DigioHypothecation($request))->triggerHypothecationCommunication($request->get('id'));
                }else{
                    (new LoanHypothecation($request))->resendNotification();
                    (new LoanHypothecation($request))->triggerHypothecationCommunication($request->get('id'));
                }
            } catch (\Exception $e) {
                //(new LoanHypothecation($request))->resendNotification();
            }
            // Send signing-link emails using the provider whose record is stored in DB.
            // DigioHypothecation reads signers[].signing_url; LoanHypothecation reads data.invitees[].signUrl.
            // We try Digio first (primary provider); if it returns 1 (no record), fall back to Leegality.

            return response()->json(['status' => 'OK', 'message' => 'Invitation re-triggered'], 200);
        }

        $application = ConsumerApplication::where('id', $request->get('id'))->first([
            'id',
            'lender_id',
            'name',
            'mobile_number',
            'email',
            'co_applicant_name',
            'co_applicant_mobile_number',
            'co_applicant_email',
            'approved_amount',
        ]);

        if (isset($application->id)) {
            $request->merge([
                'name'        => 'borrower_loan_agreement',
                'application' => $application
            ]);

            // ---- Primary: Digio ----
            $data = false;
            if(_env('DIGIO_SIGNING') == 1) {
                try {
                    $data = (new DigioHypothecation($request))->initiateHypothecation();
                } catch (\Exception $e) {
                    (new Slack(new Request([
                        'title' => 'Digio initiateHypothecation failed – falling back to Leegality',
                        'fields' => [
                            'application_id' => $request->get('id'),
                            'error' => $e->getMessage(),
                            'line' => $e->getLine(),
                            'file' => $e->getFile(),
                        ],
                        'group' => Slack::$STAGE_TESTING,
                    ])))->send();
                }
            }

            // ---- Fallback: Leegality ----
            if ($data === false) {
                $data = (new LoanHypothecation($request))->initiateHypothecation();
            }

            if ($data) {
                return response()->json([
                    'status'  => is_bool($data) ? 'FAIL' : 'OK',
                    'message' => is_bool($data) && $data
                        ? 'Loan Hypothecation Already Initiated'
                        : 'Loan Hypothecation Initiated Successfully',
                    'data'    => $data,
                ], 200);
            }
        }
        return response()->json(['status' => 'FAIL', 'message' => 'Failed to initiate Loan Hypothecation'], 400);
    }

    public function queueingRazorPayPayment($data, $customer_data){
        
        if($customer_data['pay_id']) {
            $onlinePayment = OnlinePayment::where('payment_id', $customer_data['paymentid'])->first(['id', 'application_id']);
            if (isset($onlinePayment->id)) {
                OnlinePayment::where('id', $onlinePayment->id)->update(['pay_id' => $customer_data['pay_id']]);
            }
        }

        (new Slack(new Request(['title' => 'RazorPay Webhook', 'fields' => ['data' => json_encode($data)], 'group' => Slack::$STAGE_TESTING])))->send();

        $application_id = $onlinePayment->application_id ?? 0;
        if ($data && $application_id) {

            $job_data = [
                "TXNID" => $customer_data['pay_id'],
                "TXNAMOUNT" => $customer_data['amount_paid'] / 100,
                "ORDERID" => "id_".$onlinePayment->id,
                "STATUS" => "TXN_SUCCESS",
                "application_id" => $application_id
            ];

            JobProvider::insert([
                'payload' => json_encode($job_data),
                'from' => 'razorpayPayments',
                'application_id' => $application_id,
                'available_at' => Carbon::now()->addMinutes(3)->toDateTimeString(),
                'created_at' => Carbon::now()->toDateTimeString()
            ]);
        }
        return response()->json(['status'=>'OK'], 200);
    }


    public function rajorpaymentupdate(Request $request){
        $data = ($request->all());

        //(new Slack(new Request(['title' => 'RazorPay Payment Update - Vendor Webhook', 'fields' => ['data' => json_encode($data)], 'group' => Slack::$STAGE_TESTING])))->send();

        if($data) {
            $paymentid = '';
            if (isset($data['payload']['invoice']['entity']['id'])){
                $paymentid = $data['payload']['invoice']['entity']['id'];
            }else if (isset($data['payload']['payment_link']['entity']['id'])){
                $paymentid = $data['payload']['payment_link']['entity']['id'];
            }else if(isset($data['payload']['payment']['entity']['description'])){
                $paymentid = str_replace('#', 'plink_', $data['payload']['payment']['entity']['description']);
            }

            $customer_email = '';
            if (isset($data['payload']['invoice']['entity']['customer_details']['email'])){
                $customer_email = $data['payload']['invoice']['entity']['customer_details']['email'];
            }else if (isset($data['payload']['payment']['entity']['email'])){
                $customer_email = $data['payload']['payment']['entity']['email'];
            }

            $customer_contact = '';
            if (isset($data['payload']['invoice']['entity']['customer_details']['contact'] )){
                $customer_contact = $data['payload']['invoice']['entity']['customer_details']['contact'];
            }else if (isset($data['payload']['payment']['entity']['contact'])){
                $customer_contact = $data['payload']['payment']['entity']['contact'];
            }

            $pay_id = '';
            if (isset($data['payload']['payment']['entity']['id'])){
                $pay_id = $data['payload']['payment']['entity']['id'];
            }

            $status = '';
            if (isset($data['payload']['invoice']['entity']['customer_details']['contact'] )){
                $status = $data['payload']['invoice']['entity']['status'];
            }else if (isset($data['payload']['order']['entity']['status'])){
                $status = $data['payload']['order']['entity']['status'];
            }


            $amount_paid = '';
            if (isset($data['payload']['order']['entity']['amount_paid'])){
                $amount_paid = $data['payload']['order']['entity']['amount_paid'];
            }

            //$paymentid = $data['payload']['invoice']['entity']['id'] ?? $data['payload']['payment_link']['entity']['id'];
            $customer_name = $data['payload']['invoice']['entity']['customer_details']['name'] ?? "";
            //$customer_email = $data['payload']['invoice']['entity']['customer_details']['email'] ?? $data['payload']['payment']['entity']['email'];
            //$customer_contact = $data['payload']['invoice']['entity']['customer_details']['contact'] ?? $data['payload']['payment']['entity']['contact'];
            //$status = $data['payload']['invoice']['entity']['status'] ?? $data['payload']['order']['entity']['status'];

            $updatewebhook = new WebHookLog();
            $updatewebhook->vendor = "Razorpay";
            $updatewebhook->data = json_encode($data);
            $updatewebhook->save();
            
            //For Blacksoil Razorpay Handling - Same is paytm webhook, redirecting it to paytm reco handler
            if ($status == 'paid' || $status == 'TXN_SUCCESS') {
                return $this->queueingRazorPayPayment($data, ['customer_name' => $customer_name ,'customer_contact' => $customer_contact, 'customer_email' => $customer_email, 'pay_id' => $pay_id, 'paymentid' => $paymentid, 'status' => $status, 'amount_paid' => $amount_paid]);
            }

            return response()->json(['status'=>'OK'], 200);
            
            // Not in use
            
            
            $updatewebhook = new WebHookLog();
            $updatewebhook->vendor = "Razorpay";
            $updatewebhook->data = json_encode($data);
            $updatewebhook->save();


            if ($paymentid != "") {
                if($pay_id) {
                    $onlinePayment = OnlinePayment::where('payment_id', $paymentid)->first(['id']);
                    if (isset($onlinePayment->id)) {
                        OnlinePayment::where('id', $onlinePayment->id)->update(['pay_id' => $pay_id]);
                    }
                }

                $payment = OnlinePayment::where('payment_id', $paymentid)->where('status', '!=', 'paid')->first(['id', 'application_id']);
                if (isset($payment->id)) {
                    $onlinepayment = OnlinePayment::find($payment->id);
                    $onlinepayment->name = $customer_name;
                    $onlinepayment->email = $customer_email;
                    $onlinepayment->contact = $customer_contact;
                    $onlinepayment->status = $status;
                    $onlinepayment->save();
                    // (new ConsumerApplicationController())->vendorWebhook($onlinepayment->application_id, ['type' => 'RazorPay-Webhook','status' => $status, 'data' => ['purpose' => $onlinepayment->purpose]]);
                    try{
                        $vendorWebhook = new VendorWebhook();
                        $payload = (new ConsumerApplicationController())->vendorWebhook($onlinepayment->application_id, ['type' => 'RazorPay-Webhook','status' => $status, 'data' => ['purpose' => $onlinepayment->purpose]]);
                        if (isset($payload)) {
                            $vendorWebhook->handle('RazorPay-Webhook', $payload);
                        }
                    } catch (\Exception $e){
                        $cwFactory = new CloudWatchLoggerFactory();
                        $cwFactory->logger(json_encode(['message' => $e->getMessage(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString()]));
                    }

                    if ($status == 'paid' || $status == 'TXN_SUCCESS') {

                        $bank_id = (new ConsumerApplicationController())->getTransactionBank($onlinepayment->application_id);

                        //if($onlinepayment->purpose == "emi" || $onlinepayment->purpose ="emi & penalty") {
                        $paymentfor = (isset($onlinepayment->purpose) && $onlinepayment->purpose == "processing_fee") ? 'processing_fee' : ((isset($onlinepayment->purpose) && $onlinepayment->purpose == "insurance_fee") ? 'insurance_fee' : ((isset($onlinepayment->purpose) && $onlinepayment->purpose == "advance_amount") ? 'advance_amount' : 'credit'));
                        (new LoanManagement())->paymentReconcile([
                            'payment_type' => $paymentfor,
                            'mode' => "Razorpay",
                            'paid_by' => '',
                            'application_id' => $onlinepayment->application_id,
                            'collected_by' => '',
                            'trasanction_id' => $onlinepayment->payment_id,
                            'bank_id' => $bank_id,
                            'wallet_name' => 'Razorpay',
                            'payment_date' => date('Y-m-d'),
                            'payment_reconciliation_date' => date('Y-m-d'),
                            'fore_closure_date' => $onlinepayment->foreclosure_date,
                            'amount' => $onlinepayment->amount,
                            'advance_amount' => 0,
                            'trasanction_acknowledgement' => '',
                            'online_payment_id' => $onlinepayment->id
                        ]);
                        //}
                    }
                }
            }
        }
        return response()->json(['status'=>'OK'], 200);
    }

    public function paytmPaymentWebhook(Request $request){
        $data = ($request->all());
        (new Slack(new Request(['title' => 'PAYTM Webhook', 'fields' => ['data' => json_encode($data)], 'group' => Slack::$STAGE_TESTING])))->send();
        if ($data) {
            $customer_id = $data['CUSTID'];
            $order_data = explode("_", $data['ORDERID']);
            $customer_id = $customer_id != '' ? $customer_id : $order_data['0'];
            $application = ProFormaInvoice::where('loan_application_no', $customer_id)->first(['application_id']);
            $application_id = $application->application_id ?? 0;

            JobProvider::insert([
                'payload' => json_encode($data),
                'from' => 'paytmPayments',
                'application_id' => $application_id,
                'available_at' => Carbon::now()->addMinutes(3)->toDateTimeString(),
                'created_at' => Carbon::now()->toDateTimeString()
            ]);
        }
        return response()->json(['status'=>'OK'], 200);
    }

    public function paytmpaymentupdate($data, $payment_gateway_str = 'Paytm'){
        $order_data = explode("_",$data['ORDERID']);
        if(!isset($data['application_id'])){
            $application = ProFormaInvoice::where('loan_application_no', $order_data['0'])->first(['application_id']);
            $application_id = $application->application_id;
        }else{
            $application_id = $data['application_id'];
        }
        
        $consumerApp = ConsumerApplication::where('id', $application_id)->first(['lender_id']);
        if ($consumerApp && $consumerApp->lender_id == \App\Singularity\Singularity::$lender_id) {
            return response()->json(['status' => 'OK'], 200);
        }
        if (isset($order_data[3]) and ($order_data[3] != "")){
            $payment_id_array = array($order_data[1], $order_data[2]);
        }
        else {
            $payment_id_array = array($order_data[1]);
        }
        foreach ($payment_id_array as $payment_id) {
            $onlinepayment = OnlinePayment::find($payment_id);
            try{
                $vendorWebhook = new VendorWebhook();
                $consumerApplicationController = new ConsumerApplicationController();
                $consumerApplicationController->webhook($application_id, ['type' => $payment_gateway_str.'-Webhook','status' => $data['STATUS'], 'data' => ['purpose' => $onlinepayment->purpose]]);
                $sendDAWebhook = (new WebhookController())->pushDAWebhook($application_id, 'payment');
                if ($sendDAWebhook) {
                    $consumerApplicationController->webhook($application_id, ['type' => 'DA-Confirmation-Webhook','status' => 'pending', 'data' => $consumerApplicationController->getMConnectPayload($application_id, 'DA-Confirmation-Webhook')]);
                }
                $payload = $consumerApplicationController->vendorWebhook($application_id, ['type' => $payment_gateway_str.'-Webhook','status' => $data['STATUS'], 'data' => ['purpose' => $onlinepayment->purpose]]);
                if (isset($payload)) {
                    $vendorWebhook->handle($payment_gateway_str.'-Webhook', $payload);
                }
            } catch (\Exception $e){
                $cwFactory = new CloudWatchLoggerFactory();
                $cwFactory->logger(json_encode(['message' => $e->getMessage(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString()]));
            }
            if (($onlinepayment->status != 'TXN_SUCCESS') or (!isset($onlinepayment->response))){
                    $onlinepayment->status = $data['STATUS'];
                    $onlinepayment->response = json_encode($data);
                    $onlinepayment->save();
                //(new Slack(new Request(['title' => 'PAYTM Webhook 1', 'fields' => ['data' => json_encode($data), "STATUS" => $data['STATUS']], 'group' => Slack::$STAGE_TESTING])))->send();
                if($data['STATUS'] == 'TXN_SUCCESS'){
                    try {
                        //(new Slack(new Request(['title' => 'PAYTM Webhook 2', 'fields' => ['data' => json_encode($data), "STATUS" => $data['STATUS']], 'group' => Slack::$STAGE_TESTING])))->send();
                        $data_reuse['amount'] = (int)$data['TXNAMOUNT'] ?? $onlinepayment->amount;
                        $data_reuse['payment_date'] = date('Y-m-d');
                        $data_reuse['mode'] = $payment_gateway_str;
                        $data_reuse['paid_by'] = null;
                        $data_reuse['collected_by'] = null;
                        $data_reuse['bank_id'] = (new ConsumerApplicationController())->getTransactionBank($application_id);
                        $data_reuse['wallet_name'] = null;
                        $data_reuse['application_id'] = $application_id;
                        $data_reuse['trasanction_id'] = $data['TXNID'];
                        $data_reuse['online_payment_id'] = $onlinepayment->id;
                        $data_reuse['fore_closure_date'] = isset($onlinepayment->foreclosure_date) ? $onlinepayment->foreclosure_date : '';
                        $data_reuse['trasanction_acknowledgement'] = null;
                        $data_reuse['payment_type'] = $onlinepayment->purpose ?? '';
                        $data_reuse['pre_part_payment_type'] = $onlinepayment->pre_part_payment_type ?? '';
                        $data_reuse['is_verify'] = 1;
                        (new Slack(new Request(['title' => $payment_gateway_str.' Webhook 3', 'fields' => ['data' => json_encode($data_reuse), "STATUS" => $data['STATUS']], 'group' => Slack::$STAGE_TESTING])))->send();

                        if($data_reuse['payment_type'] == 'pre_part_payment'){
                            (new RepaymentController())->checkIfRPSExists($application_id);
                            (new AccountingController())->process_pre_payment($application_id, $data_reuse);
                        }else {
                            $payment_emi = new LoanManagement();
                            $payment_emi->paymentReconcile($data_reuse);
                        }
                    } catch (\Exception $e) {
                        (new Slack(new Request(['title' => $payment_gateway_str.' Entry Error', 'fields' => ['Message' => $e->getMessage(), 'Line' => $e->getLine(), 'File' => $e->getFile()], 'group' => Slack::$STAGE_TESTING])))->send();
                    }
                }
            }
        }
        $cwFactory = new CloudWatchLoggerFactory();
        $cwFactory->logger(json_encode($data));
    }

    public function digioupdate(Request $request){
        event(new EventDigioWebhook($request->all()));
        return response()->json(['status' => 'OK'], 200);
    }

    public function digioupdatePostJob(Request $request){
        $cwFactory = new CloudWatchLoggerFactory();
        try {
            $data = ($request->all());
            //(new Slack(new Request(['title' => 'Digio VKYC Webhook', 'fields' => ['data' => json_encode($data)], 'group' => Slack::$STAGE_TESTING])))->send();
            $kid = isset($data['payload']['kyc_request']['id']) ? $data['payload']['kyc_request']['id']: $data['payload']['digilocker_request']['kyc_request_id'];
            $event_array = ['kyc.request.expired', 'documents.pulled.successfully', 'documents.pulled.partially'];
            if (isset($kid) and !in_array($data['event'], $event_array)){
                $digioVKYC = DigioVKYC::where('request_id', $kid)->whereNull('deleted_at')->first();
                $application = ConsumerApplication::with('application_element')->where('id', $digioVKYC->application_id)->first();
                if ($data['event'] == "kyc.request.created"){
                    $payload = [
                        'payload' => json_encode(array_merge(['id' => $application->id, 'kid' => $kid])),
                        'from' => 'vkycDropOff',
                        'application_id' => $application->id,
                        'available_at' => Carbon::now()->addMinute(20)->toDateTimeString(),
                        'created_at' => Carbon::now()->toDateTimeString()
                    ];
                    JobProvider::insert($payload);
                }
                $filePath = '/'.$digioVKYC->application_id.'/';
                $applicantType = explode('_', $data['payload']['kyc_request']['reference_id'])[2];
                $applicantTypestr = $applicantType == 2 ? "co_applicant_" : "";
                $digioAppType = $applicantType == 2 ? " coapplicant" : null;
                if (($data['event'] == "kyc.action.completed") and ($data['payload']['kyc_action']['status'] == "success")){
                    // update the current address, name, dob
                    $response_request = $this->digio_vkyc_response($kid, $digioVKYC->application_id);
                    (new Slack(new Request(['title'=>'Digio Action - 1','fields'=>['application_id' => $digioVKYC->application_id,], 'group' => Slack::$STAGE_TESTING])))->send();

                    foreach ($response_request['actions'] as $action){
                        if (($action['action_ref'] == 'id_proof-1') and ($data['payload']['kyc_action']['action_ref'] == 'id_proof-1')){
                            // pan card data
                            // $panDob = $action['id_card_data_response']['dob'];
                            (new Slack(new Request(['title'=>'Digio ID proof - 1','fields'=>['application_id' => $digioVKYC->application_id], 'group' => Slack::$STAGE_TESTING])))->send();
                            if (isset($action['ocr_result']['encoded_signature'])) {
                                $pan_signature = $action['ocr_result']['encoded_signature'];
                                $this->uploadtoS3Digio($filePath.$applicantTypestr.'customer_signature_from_pan.jpeg', base64_decode($pan_signature), $applicantTypestr.'customer_signature_from_pan', $digioVKYC->application_id, $applicantType, $kid, false);
                            }
                            if (isset($action['ocr_result']['encoded_image'])) {
                                $panPhoto = $action['ocr_result']['encoded_image'];
                                $this->uploadtoS3Digio($filePath.$applicantTypestr.'customer_photo_from_pan.jpeg', base64_decode($panPhoto), $applicantTypestr.'customer_photo_from_pan', $digioVKYC->application_id, $applicantType, $kid, false);
                            }
                            $uploadfid = $action['file_id'];
                            $uploadFile= $this->digio_vkyc_file($uploadfid, $digioVKYC->application_id);
                            (new Slack(new Request(['title'=>'Digio ID proof - 2','fields'=>['application_id' => $digioVKYC->application_id], 'group' => Slack::$STAGE_TESTING])))->send();
                            $this->uploadtoS3Digio($filePath.$applicantTypestr.'pan_card.jpeg', $uploadFile, $applicantTypestr.'pan_card', $digioVKYC->application_id, $applicantType, $kid);
                            if ($applicantType == 1) {
                                // $dob = explode('/', $panDob);
                                // $fDob = $dob[2].'-'.$dob[1].'-'.$dob[0];
                                $panName = $action['id_card_data_response']['name'];
                                $application->name = $panName;
                                // $application->dob = $fDob;
                                $application->save();
                            }
                        }
                        if (($action['action_ref'] == 'selfie-1') and ($data['payload']['kyc_action']['action_ref'] == 'selfie-1')){
                            // selfie image
                            (new Slack(new Request(['title'=>'Digio Selfie - 1','fields'=>['application_id' => $digioVKYC->application_id, 'api_response' => json_encode($action)], 'group' => Slack::$STAGE_TESTING])))->send();
                            $selfieFace = isset($action['face_match_result']) ? json_encode($action['face_match_result']) : '';
                            $livelinessResult = isset($action['validation_result']['LIVENESS_CHECK']) ? json_encode($action['validation_result']['LIVENESS_CHECK']) : '';
                            $selfieFile = $action['file_id'];
                            $fileString = $this->digio_vkyc_file($selfieFile, $digioVKYC->application_id);
                            (new Slack(new Request(['title'=>'Digio Selfie - 2','fields'=>['application_id' => $digioVKYC->application_id, 'file' => isset($fileString)? "true" : "false"], 'group' => Slack::$STAGE_TESTING])))->send();
                            $this->uploadtoS3Digio($filePath.$applicantTypestr.'customer_photo.jpeg', $fileString, $applicantTypestr.'customer_photo', $digioVKYC->application_id, $applicantType, $kid);
                            $digioVKYC->selfie_face_match = $selfieFace;
                            $digioVKYC->liveliness_result = $livelinessResult;
                            $digioVKYC->save();
                        }
                        if ((in_array($action['action_ref'], ['video-1', 'two_way_video-1'])) and (in_array($data['payload']['kyc_action']['action_ref'], ['video-1', 'two_way_video-1']))){
                            // video file
                            (new Slack(new Request(['title'=>'Digio VKYC - 1','fields'=>['application_id' => $digioVKYC->application_id, 'api_response' => json_encode($action)], 'group' => Slack::$STAGE_TESTING])))->send();
                            $videoFile = $action['file_id'];
                            $videoFace = isset($action['face_match_result']) ? json_encode($action['face_match_result']) : '';
                            $otpValidation = isset($action['validation_result']['OTP_STRICT']) ? json_encode($action['validation_result']['OTP_STRICT']) : '';
                            $fileString = $this->digio_vkyc_file($videoFile, $digioVKYC->application_id);
                            (new Slack(new Request(['title'=>'Digio VKYC - 2','fields'=>['application_id' => $digioVKYC->application_id, 'file' => isset($fileString)? "true" : "false"], 'group' => Slack::$STAGE_TESTING])))->send();
                            $this->uploadtoS3Digio($filePath.'vkyc_video_'.$digioVKYC->application_id.'_'.$applicantType.'.webm', $fileString, 'vkyc_video_'.$digioVKYC->application_id.'_'.$applicantType, $digioVKYC->application_id, $applicantType, $kid);
                            (new Slack(new Request(['title'=>'Digio VKYC - 3','fields'=>['application_id' => $digioVKYC->application_id, 'message' => 'uploaded to S3'], 'group' => Slack::$STAGE_TESTING])))->send();
                            $digioVKYC->video_face_match = $videoFace;
                            $digioVKYC->video_otp_validation = $otpValidation;
                            $digioVKYC->save();
                        }
                        if (($action['action_ref'] == 'digilocker-1') and ($data['payload']['kyc_action']['action_ref'] == 'digilocker-1')){
                            // aadhar data
                            (new Slack(new Request(['title'=>'Digio digilocker - 1','fields'=>['application_id' => $digioVKYC->application_id], 'group' => Slack::$STAGE_TESTING])))->send();
                            $digiFace = isset($action['face_match_result']) ? json_encode($action['face_match_result']) : '';
                            $aadharid = $aadharImage = $action['details']['aadhaar']['id_number'];
                            $aadharImage = $action['details']['aadhaar']['image'];
                            $aadharCuraddress = $action['details']['aadhaar']['current_address'];
                            $aadharPermaddress = $action['details']['aadhaar']['permanent_address'];
                            $aadharCurstate = $action['details']['aadhaar']['current_address_details']['state'];
                            $aadharCurcity = $action['details']['aadhaar']['current_address_details']['district_or_city'];
                            $aadharCurpincode = $action['details']['aadhaar']['current_address_details']['pincode'];
                            $aadharPermstate = $action['details']['aadhaar']['permanent_address_details']['state'];
                            $aadharPermcity = $action['details']['aadhaar']['permanent_address_details']['district_or_city'];
                            $aadharPermpincode = $action['details']['aadhaar']['permanent_address_details']['pincode'];
                            $this->uploadtoS3Digio($filePath.$applicantTypestr.'customer_photo_from_aadhar.jpeg', base64_decode($aadharImage), 'customer_photo_from_aadhar', $digioVKYC->application_id, $applicantType, $kid, false);
                            // zip file
                            $digilockerRid = $action['execution_request_id'];
                            $zipResponse = $this->digio_vkyc_file($digilockerRid, $digioVKYC->application_id);
                            (new Slack(new Request(['title'=>'Digio digilocker - 2','fields'=>['application_id' => $digioVKYC->application_id], 'group' => Slack::$STAGE_TESTING])))->send();
                            $tempFile = tempnam(sys_get_temp_dir(), 'temp_zip');
                            file_put_contents($tempFile, $zipResponse);
                            $zip = new \ZipArchive();
                            $zip->open($tempFile);
                            $i = 0;
                            while ($i < 2){
                                $firstFile = $zip->statIndex($i);
                                $extractedContent = $zip->getFromIndex($i);
                                if (isset($firstFile) && $firstFile) {
                                    if (str_contains($firstFile['name'], 'PAN')){
                                        $s3Name = $applicantTypestr.'digio_pan_report';
                                    } elseif (str_contains($firstFile['name'], 'ADHAR')) {
                                        $s3Name = isset($digioAppType) ? 'digio report'.$digioAppType : 'digio report applicant';
                                    }
                                    $this->uploadtoS3Digio($filePath.$s3Name.'.pdf', $extractedContent, $s3Name, $digioVKYC->application_id, $applicantType, $kid);
                                    $i++;
                                } else {
                                    break;
                                }
                            }
                            $zip->close();
                            // xml
                            $xmlAadhar = $this->digio_vkyc_file($digilockerRid, $digioVKYC->application_id, True);
                            (new Slack(new Request(['title'=>'Digio digilocker - 3','fields'=>['application_id' => $digioVKYC->application_id], 'group' => Slack::$STAGE_TESTING])))->send();
                            if (isset($xmlAadhar)) {
                                $xmlcontent = simplexml_load_string($xmlAadhar);
                                foreach ($xmlcontent->CertificateData->KycRes->UidData->Poa->attributes() as $key => $value) {
                                    if ($key == 'lm') {
                                        $landmark = (string)$value[0];
                                        break;
                                    }
                                }
                                $this->uploadtoS3Digio($filePath.$applicantTypestr.'digio_aadhar_xml.xml', $xmlAadhar, $applicantTypestr.'digio_aadhar_xml', $digioVKYC->application_id, $applicantType, $kid, false);
                            }
                            $digioVKYC->digilocker_face_match = $digiFace;
                            $digioVKYC->save();
                            if ($applicantType == 1) {
                                if ($application->application_element->vendor_id == _env('JUSPAY_VENDOR')) {
                                    $application->aadhaar_card = $aadharid;
                                }
                                $application->current_address_line_1 = $aadharCuraddress;
                                $application->current_address_state = $aadharCurstate;
                                $application->current_address_pincode = $aadharCurpincode;
                                $application->current_address_city = $aadharCurcity;
                                $application->current_address_landmark = isset($landmark) ? $landmark : "";
                                $application->permanent_address_line_1 = $aadharPermaddress;
                                $application->permanent_address_state = $aadharPermstate;
                                $application->permanent_address_city = $aadharPermcity;
                                $application->permanent_address_pincode = $aadharPermpincode;
                                $application->permanent_address_landmark = isset($landmark) ? $landmark : "";
                                $application->save();
                            }
                        }
                        if (isset($action['sub_actions'])){
                            (new Slack(new Request(['title'=>'Digio geolocation - 1','fields'=>['application_id' => $digioVKYC->application_id, 'actions' => $action['action_ref']], 'group' => Slack::$STAGE_TESTING])))->send();
                            $userGeocheck = UserGeoLocation::where('_id', $application->id)->where('applicant_type', $applicantType)->where('service', 'kyc')->first();
                            foreach ($action['sub_actions'] as $sub){
                                if (($sub['type'] == 'GEO_TAGGING') and ($sub['status'] == 'success')){
                                    // geo tagging data
                                    $geoAddress = isset($sub['details']['address']) ? $sub['details']['address'] : '';
                                    $geoLatitude = isset($sub['details']['latitude']) ? $sub['details']['latitude'] : '';
                                    $geoLongitude = isset($sub['details']['longitude']) ? $sub['details']['longitude'] : '';
                                    $geoAccuracy = isset($sub['details']['accuracy']) ? $sub['details']['accuracy'] : '';
                                }
                            }
                            if (!isset($userGeocheck)){
                                $userGeo = new UserGeoLocation();
                                $userGeo->_id = $application->id;
                                $userGeo->id_type = 'application_id';
                                $userGeo->applicant_id = $application->applicant_id ?? 0;
                                $userGeo->applicant_type = $applicantType;
                                $userGeo->service = 'kyc';
                                $userGeo->latitude = $geoLatitude;
                                $userGeo->longitude = $geoLongitude;
                                $userGeo->created_at = date('Y-m-d H:i:s');
                                $userGeo->save();
                                $consentLog = new ConsentLog();
                                $consentLog->application_id = $application->id;
                                $consentLog->ips = (new ApiController())->get_client_ip();
                                $consentLog->latitude = $geoLatitude;
                                $consentLog->longitude = $geoLongitude;
                                $consentLog->status = '1';
                                $consentLog->created_at = date('Y-m-d H:i:s');
                                $consentLog->updated_at = date('Y-m-d H:i:s');
                                $consentLog->type = 'digio_kyc';
                                $consentLog->applicant_type = $applicantType;
                                $consentLog->save();
                            } else {
                                $userGeocheck->latitude = $geoLatitude;
                                $userGeocheck->longitude = $geoLongitude;
                                $userGeocheck->created_at = date('Y-m-d H:i:s');
                                $userGeocheck->save();
                                $consentLog = ConsentLog::where('application_id', $application->id)->where('applicant_type', $applicantType)->where('type', 'digio_kyc')->first();
                                $consentLog->latitude = $geoLatitude;
                                $consentLog->longitude = $geoLongitude;
                                $consentLog->created_at = date('Y-m-d H:i:s');
                                $consentLog->updated_at = date('Y-m-d H:i:s');
                                $consentLog->save();
                            }
                            $consumerfiles = ConsumerApplicationFiles::where('consumer_application_id', $application->id)->where('file_type', 'consent_logs')->where('doc_ref_id',$kid)->get();
                            if (count($consumerfiles) == 0) {
                                (new Slack(new Request(['title'=>'Digio geolocation - 2','fields'=>['application_id' => $digioVKYC->application_id, 'actions' => $action['action_ref']], 'group' => Slack::$STAGE_TESTING])))->send();
                                if ($applicantType == 1){
                                    $view = view('admin.consumer-application.consent_logs_document_lat_long', ['data' =>
                                    [
                                        'application_id' => $application->id,
                                        'name' => $application->name,
                                        'address' => $geoAddress,
                                        'mobile' => $application->mobile_number,
                                        'latitude' => $geoLatitude,
                                        'accuracy' => $geoAccuracy,
                                        'longitude' => $geoLongitude,
                                        'consent_timestamp' => Carbon::now()->toDateTimeString(),
                                        'lender_id' => $application->lender_id
                                    ]
                                    ]);
                                } else if ($applicantType == 2) {
                                    $view = view('admin.consumer-application.consent_logs_document_lat_long', ['data' =>
                                    [
                                        'application_id' => $application->id,
                                        'name' => $application->co_applicant_name,
                                        'address' => $geoAddress,
                                        'mobile' => $application->co_applicant_mobile_number,
                                        'latitude' => $geoLatitude,
                                        'accuracy' => $geoAccuracy,
                                        'longitude' => $geoLongitude,
                                        'consent_timestamp' => Carbon::now()->toDateTimeString(),
                                        'lender_id' => $application->lender_id
                                    ]
                                    ]);
                                }
                                $pdf = App::make('snappy.pdf.wrapper');
                                $pdf->setTimeout(300);
                                $this->uploadtoS3Digio($filePath.$applicantTypestr.'consent_logs.pdf', $pdf->loadHTML($view)->output(), $applicantTypestr.'consent_logs', $digioVKYC->application_id, $applicantType, $kid);
                                (new Slack(new Request(['title'=>'Digio geolocation - 3','fields'=>['application_id' => $digioVKYC->application_id, 'actions' => $action['action_ref']], 'group' => Slack::$STAGE_TESTING])))->send();
                            }
                        }
                    }

                }
            }
            $vendorWebhook = new VendorWebhook();
            $consumerApplicationController = new ConsumerApplicationController();
            if ($data['event'] == "kyc.request.completed"){
                if ($digioVKYC->kyc_journey === 'complete' && $digioVKYC->kyc_status === 'approved'){
                    $cwFactory->logger(json_encode([
                        'title' => 'Webhook Skipped', 
                        'message' => 'Skipped completed event because KYC is already approved.', 
                        'kid' => $kid
                    ]));
                }else{
                    (new Slack(new Request(['title'=>'Digio complete - 1','fields'=>['application_id' => $digioVKYC->application_id], 'group' => Slack::$STAGE_TESTING])))->send();
                    $fileStringTwoWay = $this->digio_vkyc_report($kid, $digioVKYC->application_id);
                    $this->uploadtoS3Digio($filePath.'vkyc_report_'.$digioVKYC->application_id.'_'.$applicantType.'.pdf', $fileStringTwoWay, 'vkyc_report_'.$digioVKYC->application_id.'_'.$applicantType, $digioVKYC->application_id, $applicantType, $kid);
                    
                    $digioVKYC->kyc_journey = 'complete';
                    $digioVKYC->save();
                    $response_request = $this->digio_vkyc_response($kid, $digioVKYC->application_id);
                    (new Slack(new Request(['title'=>'Digio complete - 2','fields'=>['application_id' => $digioVKYC->application_id], 'group' => Slack::$STAGE_TESTING])))->send();
                    $kyc = KYCDetails::where('application_id', $digioVKYC->application_id)->whereNull('deleted_at')->where('request_id', $kid)->first();
                    $kyc->response = json_encode([$response_request]);
                    $kyc->updated_at = Carbon::now()->toDateTimeString();
                    $kyc->save();
                    $this->uploadtoS3Digio($filePath.$applicantTypestr.'digio_data.json', json_encode($response_request), $applicantTypestr.'digio_data', $digioVKYC->application_id, $applicantType, $kid, false);
                    try {
                        $consumerApplicationController->webhook($digioVKYC->application_id, ['type' => 'VKYC-Webhook','status' => 'completed', 'data' => ['vendor'=> 'Digio', 'applicantType' => $applicantType]]);
                        $payload = $consumerApplicationController->vendorWebhook($digioVKYC->application_id, ['type' => 'Digio-VKYC-Webhook','status' => 'completed', 'data' => []]);
                        if (isset($payload)) {
                            $vendorWebhook->handle('Digio-VKYC-Webhook', $payload);
                        }
                    } catch (\Exception $e){
                        $cwFactory->logger(json_encode(['title' => 'Webhook failed', 'message' => $e->getMessage(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString()]));
                    }
                    $payload = [
                        'payload' => json_encode(array_merge(['id' => $application->id, 'kid' => $kid])),
                        'from' => 'digioKYCSlack',
                        'application_id' => $application->id,
                        'available_at' => Carbon::now()->addMinute(2)->toDateTimeString(),
                        'created_at' => Carbon::now()->toDateTimeString()
                    ];
                    JobProvider::insert($payload);
                }
            }
            if ($data['event'] == "kyc.request.approved"){

                if (!isset($digioVKYC)){
                    $digioVKYC = DigioVKYC::where('request_id', $kid)->whereNull('deleted_at')->first();
                }

                if (!isset($applicantType)){
                    $applicantType = explode('_', $data['payload']['kyc_request']['reference_id'])[2];
                }

                if (!isset($filePath)){
                    $filePath = '/'.$digioVKYC->application_id.'/';
                }

                $fileStringTwoWay = $this->digio_vkyc_report($kid, $digioVKYC->application_id);
                $this->uploadtoS3Digio($filePath.'vkyc_report_'.$digioVKYC->application_id.'_'.$applicantType.'.pdf', $fileStringTwoWay, 'vkyc_report_'.$digioVKYC->application_id.'_'.$applicantType, $digioVKYC->application_id, $applicantType, $kid);

                $digioVKYC->kyc_status = 'approved';
                $digioVKYC->save();

                DB::table('consumer_application_files')->where('consumer_application_id', $digioVKYC->application_id)->where('file_type', 'customer_photo')->where('doc_ref_id', $kid)->update(['doc_verify' => 1]);
                try {
                    $consumerApplicationController->webhook($digioVKYC->application_id, ['type' => 'VKYC-Webhook','status' => 'approved', 'data' => ['vendor'=> 'Digio', 'applicantType' => $applicantType]]);
                    $sendDAWebhook = (new WebhookController())->pushDAWebhook($digioVKYC->application_id, 'vkyc');
                    if ($sendDAWebhook) {
                        $consumerApplicationController->webhook($digioVKYC->application_id, ['type' => 'DA-Confirmation-Webhook','status' => 'pending', 'data' => $consumerApplicationController->getMConnectPayload($digioVKYC->application_id, 'DA-Confirmation-Webhook')]);
                    }
                    $payload = $consumerApplicationController->vendorWebhook($digioVKYC->application_id, ['type' => 'Digio-VKYC-Webhook','status' => 'approved', 'data' => []]);
                    if (isset($payload)) {
                        $vendorWebhook->handle('Digio-VKYC-Webhook', $payload);
                    }
                } catch (\Exception $e){
                    $cwFactory->logger(json_encode(['title'=> 'Webhook failed','message' => $e->getMessage(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString()]));
                }


                $this->getDigioCustomerPhoto($kid, $digioVKYC->application_id, $applicantType);
            }
            if ($data['event'] == "kyc.request.rejected"){
                $data = ConsumerApplication::with([
                    'merchant' => function ($query) {
                        $query->select('id', 'merchant_name');  // Select necessary fields from Merchant
                    },
                    'advisor' => function ($query) {
                        $query->select('id', 'name', 'email');  // Select necessary fields from Advisor
                    }
                ])
                ->where('id', $digioVKYC->application_id)
                ->whereNull('deleted_at')
                ->first(['id', 'name', 'merchant_id', 'created_by','co_applicant_name']);  // Include foreign keys
                // Ensure data exists to avoid errors
                if ($data) {
                    $name = $applicantType == 2 ? $data->co_applicant_name : $data->name;

                    $commentText = "Dear " . $data->advisor->name . ",<br><br>The 1 way KYC has been rejected for partner loan id " . $digioVKYC->application_id . ". Kindly generate a new 1 way KYC  link on Credit Fair Admin portal and complete the 1 way KYC .<br> Customer Name : " . $name . "<br> Merchant Name: " . $data->merchant->merchant_name;

                    $comment = new Comments();
                    $comment->application_id = $digioVKYC->application_id;
                    $comment->user_id = 107;
                    $comment->comment = $commentText;
                    $comment->show_merchant = 0;
                    $comment->show_consumer = 0;
                    $comment->save();

                    $email = $data->advisor->email ?? "" ;

                    if ($email != "") {
                        $body = '
                        <div style="font-size:13px;font-family:verdana,arial;line-height:1.5">
                        Dear ' . $data->advisor->name . ',
                        The 1 way KYC has been rejected for partner loan id ' . $digioVKYC->application_id .'<br><br>
                        Kindly generate a new 1 way KYC link on Credit Fair Admin portal and complete the 1 way KYC .<br> Customer Name : ' . $name . '<br> Merchant Name: ' . $data->merchant->merchant_name.'<br>Commented By: System Generated<br><br>
                        </div>';

                        Mail::send('emails.reminders.basic_reminder',
                            ['body' => $body]
                            , function ($message) use ($email) {
                                $message->to([$email])->subject('VKYC Rejected');
                        });
                    }
                }
                $digioVKYC->kyc_status = 'rejected';
                $digioVKYC->save();
                try {
                    $consumerApplicationController->webhook($digioVKYC->application_id, ['type' => 'VKYC-Webhook','status' => 'rejected', 'data' => ['vendor'=> 'Digio', 'applicantType' => $applicantType]]);
                    $payload = $consumerApplicationController->vendorWebhook($digioVKYC->application_id, ['type' => 'Digio-VKYC-Webhook','status' => 'rejected', 'data' => []]);
                    if (isset($payload)) {
                        $vendorWebhook->handle('Digio-VKYC-Webhook', $payload);
                    }
                } catch (\Exception $e){
                    $cwFactory->logger(json_encode(['title' =>'Webhook failed', 'message' => $e->getMessage(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString()]));
                }
            }
            return response()->json(['status'=>'OK'], 200);
        }catch (\Exception $e){
            $cwFactory->logger(json_encode(['message' => $e->getMessage(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString()]));
            $cwFactory->logger(json_encode(['digio_api_response' => json_encode($response_request ?? '')]));
            return response()->json(['message'=>'Exception occurred while digio post job update'], 400);
        }
    }

    public function getDigioCustomerPhoto($kid, $application_id, $applicantType){
        try {
            $this->digio_url = _env('DIGIO_DOMAIN_V3') . 'client/kyc/v2/' . $kid . '/response';

            $DIGIO_AUTH_HEADER = (_env('DIGIO_AUTH_HEADER', ''));
            $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => $this->digio_url,
                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_HTTPHEADER => ['Authorization:Basic ' . $DIGIO_AUTH_HEADER],
            ));
            $response = curl_exec($curl);
            curl_close($curl);

            $responseData = json_decode($response, 1);

            $file_type = $applicantType == 1 ? 'customer_photo' : 'co_applicant_customer_photo';

            $processed = [];
            foreach ($responseData['actions'] as $action) {
                if ($action['type'] == 'two_way_video') {
                    foreach ($action['sub_actions'] as $sub_actions) {
                        if ($sub_actions['type'] == 'FRAME_CAPTURE' && $sub_actions['sub_action_ref'] == 'frame_capture-1') {

                            if (!isset($processed[$applicantType]) && !isset($sub_actions['ocr_result'])) {

                                $file_id = $sub_actions['file_id'];
                                $uploadFile = $this->digio_vkyc_file($file_id, $application_id);
                                (new Slack(new Request(['title' => 'Digio Profile Photo', 'fields' => ['application_id' => $application_id], 'group' => Slack::$STAGE_TESTING])))->send();

                                $this->uploadtoS3Digio('/' . $application_id . '/' . $file_type . '.jpeg', $uploadFile, $file_type, $application_id, $applicantType, $kid);

                                $processed[] = $applicantType;
                            }
                        }
                    }
                }
            }
        }catch (\Exception $e){

        }
    }

    public function fetchDigioCustomerPhotoManually(Request $request){
        $digioVKYC = DigioVKYC::where('application_id', $request->get('application_id'))->whereNull('deleted_at')->get(['request_id', 'application_id', 'applicant_type']);
        foreach($digioVKYC as $_digioVKYC) {

            $file_type = $_digioVKYC->applicant_type == 1 ? 'customer_photo' : 'co_applicant_customer_photo';

            $isExist = ConsumerApplicationFiles::where('consumer_application_id', $request->get('application_id'))->where('file_type', $file_type)->first(['id']);
            if (isset($isExist->id)){
                continue;
            }

            (new ApiController())->getDigioCustomerPhoto($_digioVKYC->request_id, $_digioVKYC->application_id, $_digioVKYC->applicant_type);
        }
    }

    public function getAccountAggregatorWebhook(Request $request){
        (new Slack(new Request(['title'=>'AA - Integration','fields'=>['res' => json_encode($request->all())], 'group' => Slack::$STAGE_TESTING])))->send();

        event(new EventAccountAggregatorWebhook($request->all()));

        /*$payload = [
            'payload' => json_encode($request->all()),
            'from' => 'account_aggregator',
            'application_id' => 181,
            'available_at' => Carbon::now()->addMinutes(10)->toDateTimeString(),
            'created_at' => Carbon::now()->toDateTimeString()
        ];
        JobProvider::insert($payload);*/

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

    public function pirimidFetchAnalytics(Request $request){

        event(new EventPirimidWebhook($request->all()));
        return response()->json(['status' => 'OK'], 200);
    }

    public function digio_vkyc_response($id, $application_id){
        $this->digio_url = _env('DIGIO_KYC_URL');
        $appln = ConsumerApplication::where('id', $application_id)->first(['lender_id']);
        $lender_id = isset($appln->lender_id) ? $appln->lender_id : 0;
        if($lender_id == KMGP2P::$lender_id){
            $DIGIO_CLIENT_ID = (_env('KMGP2P_DIGIO_CLIENT_ID', ''));
            $DIGIO_CLIENT_SECRET = (_env('KMGP2P_DIGIO_CLIENT_SECRET', ''));
        } else {
            $DIGIO_CLIENT_ID = (_env('DIGIO_CLIENT_ID', ''));
            $DIGIO_CLIENT_SECRET = (_env('DIGIO_CLIENT_SECRET', ''));
        }

        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $this->digio_url . $id . "/response",
            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_HTTPHEADER => ['Authorization:Basic ' . base64_encode($DIGIO_CLIENT_ID . ':' . $DIGIO_CLIENT_SECRET)],
        ));
        $response = curl_exec($curl);
        curl_close($curl);
        return json_decode($response, true);
    }

    public function digio_vkyc_file($fid, $application_id, $xml=False){
        if ($xml == True){
        $this->digio_url = _env('DIGIO_KYC_URL')."media/" . $fid . '?doc_type=AADHAAR&xml=True';
        }
        else {
            $this->digio_url = _env('DIGIO_KYC_URL')."media/" . $fid;
        }
        $appln = ConsumerApplication::where('id', $application_id)->first(['lender_id']);
        $lender_id = isset($appln->lender_id) ? $appln->lender_id : 0;
        if($lender_id == KMGP2P::$lender_id){
            $DIGIO_CLIENT_ID = (_env('KMGP2P_DIGIO_CLIENT_ID', ''));
            $DIGIO_CLIENT_SECRET = (_env('KMGP2P_DIGIO_CLIENT_SECRET', ''));
        } else {
            $DIGIO_CLIENT_ID = (_env('DIGIO_CLIENT_ID', ''));
            $DIGIO_CLIENT_SECRET = (_env('DIGIO_CLIENT_SECRET', ''));
        }
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $this->digio_url,
            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 => ['Authorization:Basic ' . base64_encode($DIGIO_CLIENT_ID . ':' . $DIGIO_CLIENT_SECRET)],
        ));
        $response = curl_exec($curl);
        curl_close($curl);
        return $response;
    }

    public function digio_vkyc_report($fid, $application_id, $xml=False){
        $this->digio_url = _env('DIGIO_DOMAIN_V3').'client/kyc/v3/'.$fid.'/kyc_report';
        $appln = ConsumerApplication::where('id', $application_id)->first(['lender_id']);
        $lender_id = isset($appln->lender_id) ? $appln->lender_id : 0;
        
        $DIGIO_AUTH_HEADER = (_env('DIGIO_AUTH_HEADER', ''));
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $this->digio_url,
            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_HTTPHEADER => ['Authorization:Basic ' . $DIGIO_AUTH_HEADER],
        ));
        $response = curl_exec($curl);
        curl_close($curl);

        return $response;

    }


    public function partnerLinkCheckBureau(Request $request) {
        $data = ($request->all());
        $skip_pan_validation = (bool) (_env('SKIP_PAN_VALIDATION') ?? false);
        $bureauData = array(
            "application_id" => $data['application_id'],
            "applicant_type" => $data['applicant_type'],
            "request_type" => "customer",
            "first_name" => $data['first_name'],
            "last_name" => $data['last_name'],
            "pan_card" => $data['pan_card'],
            "document_type" => "PAN_DETAILED",
            "consent" => "Y",
            "mobile_number" => $data['mobile_number'],
            "gender" => "1",
            "dob" => $data['dob'],
            "address" => $data['address'],
            "state" => $data['state'],
            "city" => $data['city'],
            "postal_code" => $data['postal_code'],
            "loan_amount" => 100000,
            "vendor" => "partner link",
            "skip_pan_validation" => $skip_pan_validation
        );
        $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => str_replace("-soft", "", _env('EXPERIAN_SOFT_PULL_HOST')),
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => "",
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 120,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => "POST",
                CURLOPT_POSTFIELDS => json_encode($bureauData),
                CURLOPT_HTTPHEADER => array(
                    "Content-Type: application/json",
                    "X-Client-Id: "._env('EXPERIAN_SOFT_PULL_ID'),
                    "X-Client-Secret: "._env('EXPERIAN_SOFT_PULL_SECRET'),
                ),
            ));
            $res = curl_exec($curl);
            $data = json_decode($res, 1);
            $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
            $err = curl_error($curl);
            curl_close($curl);
            $cwFactory = new CloudWatchLoggerFactory();
            $cwFactory->logger(json_encode(json_encode(['bureau_response' => json_encode($res), 'http_code' => $httpcode])));
            return response()->json(['res'=> $res, 'code' => $httpcode], 200);
    }

    public function noTouchCheckBureau(Request $request) {
        $cwFactory = new CloudWatchLoggerFactory();
        $data = ($request->all());
        $skip_pan_validation = (bool) (_env('SKIP_PAN_VALIDATION') ?? false);

        // Bureau API request
        $bureauData = array(
            "application_id" => $data['application_id'],
            "applicant_type" => $data['applicant_type'],
            "request_type" => "customer",
            "first_name" => $data['first_name'],
            "last_name" => $data['last_name'],
            "pan_card" => $data['pan_card'],
            "document_type" => "PAN_DETAILED",
            "consent" => "Y",
            "mobile_number" => $data['mobile_number'],
            "gender" => "1",
            "dob" => $data['dob'],
            "address" => $data['address'],
            "state" => $data['state'],
            "city" => $data['city'],
            "postal_code" => $data['postal_code'],
            "loan_amount" => isset($data['loan_amount']) ? $data['loan_amount'] : 100000,
            "vendor" => "no_touch",
            "skip_pan_validation" => $skip_pan_validation
        );
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => isset($data['url']) ? $data['url'] : str_replace("soft-bureau", "credit", _env('EXPERIAN_SOFT_PULL_HOST')),
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 120,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => json_encode($bureauData),
            CURLOPT_HTTPHEADER => array(
                "Content-Type: application/json",
                "X-Client-Id: "._env('EXPERIAN_SOFT_PULL_ID'),
                "X-Client-Secret: "._env('EXPERIAN_SOFT_PULL_SECRET'),
            ),
        ));
        $res = curl_exec($curl);
        $resp_data = json_decode($res, 1);
        $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        $err = curl_error($curl);
        curl_close($curl);
        $cwFactory->logger(json_encode(json_encode(['bureau_response' => json_encode($res), 'http_code' => $httpcode])));

        if ($httpcode == 200) {
            $panValidationData = array(
                "application_id" => $data['application_id'],
                "applicant_type" => $data['applicant_type'],
                "pan_card" => $data['pan_card'],
                "dob" => $data['dob'],
                "document_type" => "PAN_DETAILED",
                "first_name" => $data['first_name'],
                "last_name" => $data['last_name'],
                "vendor" => "no_touch",
                "skip_pan_validation" => $skip_pan_validation
            );
            $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => str_replace("get-soft-bureau-response", "validate-pan", _env('EXPERIAN_SOFT_PULL_HOST')),
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => "",
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 120,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => "POST",
                CURLOPT_POSTFIELDS => json_encode($panValidationData),
                CURLOPT_HTTPHEADER => array(
                    "Content-Type: application/json"
                ),
            ));
            $validation_res = curl_exec($curl);
            $validation_data = json_decode($validation_res, 1);
            // $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
            $validation_err = curl_error($curl);
            curl_close($curl);
            $cwFactory->logger(json_encode(json_encode(['pan_validation_response' => json_encode($validation_res)])));
        }
        return response()->json(['res'=> $res, 'code' => $httpcode], 200);
    }

    public function uploadtoS3Digio($path, $content, $file_type, $id, $appType, $ref_id, $dbUpload=true){
        $s3 = Storage::disk('s3');
        $s3->put($path, $content);
        // $data['file_type'] = $file_type;
        // $data['id'] = $id;
        // (new ConsumerApplicationController())->getUploadedFileNameMultiple($s3, $id.'/', $data);
        if ($dbUpload) {
            $existing_data = ConsumerApplicationFiles::where('consumer_application_id', $id)->where('file_path', 'LIKE', '%' . $id.'/' . '%')->get(['file_path', 'doc_ref_id']);
            $existingfiles = array();
            $existingkid = array();
            foreach ($existing_data as $existingfile) {
                array_push($existingfiles, $existingfile->file_path);
                $existingkid[$existingfile->file_path]['kid'] = $existingfile->doc_ref_id;
            }
            if (!in_array(substr($path, 1), $existingfiles) || $file_type == 'consent_logs') {
                $consumer_application_file = new ConsumerApplicationFiles();
                $consumer_application_file->consumer_application_id = $id;
                $consumer_application_file->file_type = $file_type;
                $consumer_application_file->bank_name = "";
                $consumer_application_file->password = "";
                $consumer_application_file->accounttype = "";
                $consumer_application_file->statementtype = "";
                $consumer_application_file->statemenfilettype = "";
                $consumer_application_file->customer_id = "";
                $consumer_application_file->provider = "";
                $consumer_application_file->finbit_analysis_date = null;
                $consumer_application_file->bp_number = "";
                $consumer_application_file->accountUID = "";
                $consumer_application_file->file_path = substr($path, 1);
                $consumer_application_file->created_by = (Auth::check()) ? Auth::user()->id : null;
                $consumer_application_file->image_score = 0;
                $consumer_application_file->m_generated = 0;
                $consumer_application_file->applicant_type = $appType;
                $consumer_application_file->bureau_report_type = "";
                $consumer_application_file->bureau_report_score = "";
                $consumer_application_file->is_masked = 0;
                $consumer_application_file->doc_ref_id = $ref_id;
                $consumer_application_file->save();
            } else {
                if ($ref_id != $existingkid[substr($path, 1)]['kid']) {
                    $consumer_application_file = ConsumerApplicationFiles::where('consumer_application_id', $id)->where('applicant_type', $appType)->where('file_type', $file_type)->first();
                    $consumer_application_file->file_type = $file_type;
                    $consumer_application_file->file_path = substr($path, 1);
                    $consumer_application_file->doc_ref_id = $ref_id;
                    $consumer_application_file->save();
                }
            }
        }

    }

    public function karzaKYCrequest ($id) {
        $response = (new ConsumerApplicationController())->requestkarzakyc($id);
        return $response;
        // $data['customer_link'] = "https://prfs.in/PERFOS/7a5Vly3";
        // $data['co_customer_link'] = "https://prfs.in/PERFOS/dsAGhjP";
        // return \response()->json(array_merge(['status' => 'OK'], $data), 200);
    }

    public function digioKYCSlack ($job, $payload) {
        if (isset($payload->kid)) {
            $kycRecord = DigioVKYC::where('request_id', $payload->kid)->whereNull('deleted_at')->first();
            $consumerDetails = ConsumerApplication::with('application_element')->where('id', $kycRecord->application_id)->first();
            $vendor = Vendor::where('id', $consumerDetails->application_element->vendor_id)->first();
            if ($kycRecord->kyc_status != 'approved') {
                if ($kycRecord->applicant_type == 1) {
                    $name = $consumerDetails->name;
                    $email = $consumerDetails->email;
                    $mobile_number = $consumerDetails->mobile_number;
                    $vendorName = isset($vendor) ? $vendor->name : "Creditfair";
                    (new Slack(new Request(['title' => 'KYC Pending', 'fields' => ['Applicant Type' => 'Primary Applicant', 'Co-Applicant Name' => $name, 'Email' => $email, 'Phone Number' => $mobile_number, 'Module/Merchant' => $vendorName, 'dashboard URL' => _env('DIGIO_DRIVE').'/#/kyc/requests/details/'.$payload->kid.'//', 'Status' => 'KYC PENDING', 'Application ID' => $payload->id, 'Application Link' => _env('APP_URL').'/admin/consumer-applications/edit/'.$payload->id], 'group' => Slack::$JUSPAY_DIGIO])))->send();
                    $mail_message = "Applicant Type: Primary Applicant<br/>Applicant Name: ".$name."<br/>Email: ".$email."<br/> Phone Number: ".$mobile_number."<br/>Module/Merchant: ".$vendorName." <br/>Digio Dashboard Link: "._env('DIGIO_DRIVE')."/#/kyc/requests/details/".$payload->kid."//" ."<br/>Status: KYC Pending <br/>Application ID: ".$consumerDetails->id."<br/>Application Link: "._env('APP_URL')."/admin/consumer-applications/edit/".$payload->id;
                    $cc = explode(',', _env('DIGIO_CC'));
                    Mail::send('emails.reminders.basic_reminder',
                        [
                            'body' => $mail_message
                        ]
                        , function ($message) use ($cc, $consumerDetails) {
                            $message->to(_env('DIGIO_MAIL'))->subject('APP ID - '.$consumerDetails->id.' KYC PENDING - JusPay');
                            $message->cc($cc);
                        });
                } else {
                    $name = $consumerDetails->co_applicant_name;
                    $email = $consumerDetails->co_applicant_email;
                    $mobile_number = $consumerDetails->co_applicant_mobile_number;
                    $vendorName = isset($vendor) ? $vendor->name : "Creditfair";
                    (new Slack(new Request(['title' => 'KYC Pending', 'fields' => ['Applicant Type' => 'Co-Applicant', 'Co-Applicant Name' => $name, 'Email' => $email, 'Phone Number' => $mobile_number, 'Module/Merchant' => $vendorName, 'dashboard URL' => _env('DIGIO_DRIVE').'/#/kyc/requests/details/'.$payload->kid.'//', 'Status' => 'KYC PENDING', 'Application ID' => $payload->id, 'Application Link' => _env('APP_URL').'/admin/consumer-applications/edit/'.$payload->id], 'group' => Slack::$JUSPAY_DIGIO])))->send();
                    $mail_message = "Applicant Type: Co-Applicant<br/>Co-Applicant Name: ".$name."<br/>Email: ".$email."<br/> Phone Number: ".$mobile_number."<br/>Module/Merchant: ".$vendorName." <br/>Digio Dashboard Link: "._env('DIGIO_DRIVE')."/#/kyc/requests/details/".$payload->kid."//" ."<br/>Status: KYC Pending <br/>Application ID: ".$consumerDetails->id."<br/>Application Link: "._env('APP_URL')."/admin/consumer-applications/edit/".$payload->id;
                    $cc = explode(',', _env('DIGIO_CC'));
                    Mail::send('emails.reminders.basic_reminder',
                        [
                            'body' => $mail_message
                        ]
                        , function ($message) use ($cc, $consumerDetails) {
                            $message->to(_env('DIGIO_MAIL'))->subject('APP ID - '.$consumerDetails->id.' KYC PENDING - JusPay');
                            $message->cc($cc);
                        });
                }
            }
        }
    }

    public function vkycDropOff ($job, $payload) {
        if (isset($payload->kid)) {
            $kycRecord = DigioVKYC::where('request_id', $payload->kid)->whereNull('deleted_at')->first();
            $consumerDetails = ConsumerApplication::where('id', $kycRecord->application_id)->first(['id', 'created_by']);
            $kycResponse = $this->digio_vkyc_response($payload->kid, $kycRecord->application_id);
            $actionArray = [];
            foreach ($kycResponse['actions'] as $action){
                if (!isset($action['completed_at'])) {
                    array_push($actionArray, $action['action_ref']);
                }
            }
            if (count($actionArray) > 0) {
                $title = 'VKYC Pending for '.$consumerDetails->id;
                if (isset($consumerDetails->created_by)) {
                    $userDetails = User::find($consumerDetails->created_by);
                }
                $slack_id = $userDetails->slack_id;
                $encodedURL = urlencode($kycRecord->kyc_request_url);
                $shortUrl = Shortio::getUrl($encodedURL);
                if(isset($slack_id) && $slack_id != "") {
                    (new Slack(new Request(['title' => $title, 'channel' => $slack_id, 'fields' => ['Application ID' => $consumerDetails->id, 'Applicant Type' => $kycRecord->applicant_type, 'Steps Pending' => json_encode($actionArray), 'KYC URL' => $shortUrl, 'VKYC Created at' => $kycRecord->created_at->toDateString()]] )))->send_dm();
                }
            }
        }
    }

    public function appReview(Request $request){
        $file = $request->has('f') ? $request->get('f') : '';
        $agreement = $request->has('tt') ? $request->get('tt') : '';
        $id = $request->has('i') ? $request->get('i') : '';
        $file_type = str_replace(' ','_',strtolower($agreement));
        if($file){
            //$file_path = explode('https://s3.'._env('AWS_DEFAULT_REGION').'.amazonaws.com/'._env('AWS_BUCKET').'/', $file);
            $file_path = explode('/documents/',$file);
            $file_path = explode('/',$file_path[1]);
            $file_path = base64_decode($file_path[2]);
            if(isset($file_path[1])){
                ConsumerApplicationFiles::where('id',$id)
                    ->where('file_type',$file_type)->where('file_path',$file_path)
                    ->where('is_reviewed',0)
                    ->update(['is_reviewed' => 1]);
            }
        }
    }

    public function validatePayment(Request $request){
        $status = 'OK';
        $message = '';
        if($request->has('id') && $request->get('id') > 0){
            $minimumAmount = 500;
            $id = $request->get('id');
            $customAmount = $request->has('f_amt') ? $request->get('f_amt') : 0;
            $data = (new FrontController())->getPaymentData($request->get('id'));
            $consumerApplication = ConsumerApplication::find($id);

            $maxAmount = $data['max_amount'];
            $payable = $data['total_pending_til_date'];
            if($payable > $maxAmount){
                $maxAmount = $payable;
            }
            if($payable < $minimumAmount){
                $minimumAmount = $payable;
            }

            if ($data) {
                $razorPayData['email'] = "";
                $razorPayData['lender_id'] = $consumerApplication->lender_id;
                $razorPayData['id'] = $id;
                $razorPayData['purpose'] = 'emi';
                $razorPayData['emi_date'] = $data['emi_date'];
                $razorPayData['custom_date'] = Carbon::now()->toDateString();
                if($customAmount > 0) {
                    //pay custom amount
                    if ($customAmount > 0 && $customAmount >= $minimumAmount && $customAmount <= $maxAmount) {
                        $razorPayData['amount'] = $customAmount;

//                        $consumerApplication = ConsumerApplication::find($id);
//                        $hashids = new Hashids('Creditfair by CS', 20);
//                        $hashed_id = $hashids->encode($id);
//                        //$customAmountHash = $hashids->encode($customAmount);
//                        $customAmountHash = base64_encode(wall_encrypt($customAmount));
//
//                        $message = (asset("paytm/" . $hashed_id . "?data=" . $customAmountHash));
//
//                        try {
//                            $message = \Bitly::getUrl($message);
//                        }catch (\Exception $e){
//                        }

                        //$message = $this->getPaymentLink($customAmount, $consumerApplication->lender_id, $id, $data['emi_date']);

                    }elseif($customAmount < $minimumAmount){
                        $status = 'FAIL';
                        $message = 'Amount should be greater than '.$minimumAmount;
                    }elseif($customAmount > $maxAmount){
                        $status = 'FAIL';
                        $message = 'Amount should be less than '.$maxAmount;
                    }
                }else{
                    //pay your emi amount
                    $razorPayData['amount'] = $payable;
//                    $hashids = new Hashids('Creditfair by CS', 20);
//                    $hashed_id = $hashids->encode($id);
//                    $customAmountHash = base64_encode(wall_encrypt($payable));
//                    $message = (asset("paytm/" . $hashed_id . "?data=" . $customAmountHash));
//                    try {
//                        $message = \Bitly::getUrl($message);
//                    }catch (\Exception $e){
//                    }
//                    $total_pending_til_date = $data['total_pending_til_date'];
//                    $message = $this->getPaymentLink($total_pending_til_date, $consumerApplication->lender_id, $id, $data['emi_date']);
                }

                if(isset($razorPayData['amount']) && $razorPayData['amount'] > 0){
                    $message = (new ConsumerApplicationController())->getrazorpaylink($razorPayData);
                }
            }
        }else{
            $status = 'FAIL';
            $message = 'Invalid request';
        }

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

    public function getPaymentLink($amount, $lender_id, $id, $emi_date){
        $consumerController = new ConsumerApplicationController();
        $razorPayData['amount'] = $amount;
        $razorPayData['email'] = "";
        $razorPayData['lender_id'] = $lender_id;
        $razorPayData['id'] = $id;
        $razorPayData['purpose'] = 'emi';
        $razorPayData['emi_date'] = $emi_date;
        $razorPayData['custom_date'] = Carbon::now()->toDateString();
        return $consumerController->getrazorpaylink($razorPayData);
    }

    public function emiPayment($message){
        $url = self::wall_decrypt($message);
        return Redirect::to($url);
    }

    public static function wall_encrypt($message)
    {
        $max_msg_size = 1000;
        $message = substr($message, 0, $max_msg_size);

        $password = 'CRDRIAF';

        $salt = sha1(mt_rand());

        $iv = substr(sha1(mt_rand()), 0, 16);

        $encrypted = openssl_encrypt(
            "$message", 'aes-256-cbc', "$salt:$password", null, $iv
        );

        return str_replace('/','*#',"$salt:$iv:$encrypted");
    }

    public static function wall_decrypt($msg_bundle)
    {

        $msg_bundle = str_replace('/','*#',$msg_bundle);
        $password = 'CRDRIAF';
        $saved_bundle = $msg_bundle;

        $components = explode( ':', $saved_bundle );;

        //var_dump($components);

        $salt          = $components[0];
        $iv            = $components[1];
        $encrypted_msg = $components[2];

        $decrypted_msg = openssl_decrypt(
            "$encrypted_msg", 'aes-256-cbc', "$salt:$password", null, $iv
        );

        if ( $decrypted_msg === false ) {
            die("Unable to decrypt message! (check password) \n");
        }

        $msg = substr( $decrypted_msg, 41 );
        return $decrypted_msg;
    }

    public function paytmValidation(Request $request){

        try {
            $response = [];
            $status = 'FAIL';
            $defaultMessage = 'It seems the details that you entered are wrong. Please enter correct details and try again.';
            if (!$request->has('account_number') || empty($request->get('account_number'))) {
                $response = ['status' => $status, 'message' => $defaultMessage, 'code' => 'CFE00455'];
            } elseif (!$request->has('mobile_number') || empty($request->get('mobile_number'))) {
                $response =  ['status' => $status, 'message' => $defaultMessage, 'code' => 'CFE00454'];
            }

            if (empty($response)) {
                $invoice = ProFormaInvoice::where('loan_application_no', $request->get('account_number'))->first(['application_id']);
                if (isset($invoice->application_id)) {
                    $application = ConsumerApplication::where('id', $invoice->application_id)->where('mobile_number', $request->get('mobile_number'))->whereIn('state', ['disbursed', 'nach registered'])->whereNull('is_deleted')->first(['id', 'name', 'state']);
                    if (isset($application->id)) {
                        $status = 'OK';
                        $message = 'Successfully fetched account details';

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

                        if (isset($payment[$application->id]) && isset($payment[$application->id]['amount_due']) && $payment[$application->id]['amount_due']) {
                            $data = [
                                'account_number' => $request->get('account_number'),
                                'customer_name' => $application->name,
                                'due_amount' => $payment[$application->id]['amount_due'],
                                'min_amount' => $payment[$application->id]['amount_due'],
                                'max_amount' => $payment[$application->id]['amount_pending'],
                                'mobile_number' => $request->get('mobile_number'),
                            ];
                            $response = ['status' => $status, 'message' => $message, 'data' => $data, 'code' => 'CFE00452'];
                        } else {
                            $message = 'There are no pending dues for the details';
                            $response = ['status' => $status, 'message' => $message, 'code' => 'CFE00453'];
                        }
                    } else {
                        $response = ['status' => $status, 'message' => $defaultMessage, 'code' => 'CFE00454'];
                    }
                } else {
                    $response = ['status' => $status, 'message' => $defaultMessage, 'code' => 'CFE00455'];
                }
            }
        }catch (\Exception $e){
            $message = 'Couldn\'t connect to the server. Please try again later.';
            $response = ['status' => $status, 'message' => $message, 'code' => 'CFE00501'];
        }

        return response()->json($response);
    }

    public function paytmReconciliation(Request $request){

        try {
            $response = [];
            $status = 'FAIL';
            $message = '';
            $defaultMessage = 'It seems the details that you entered are wrong. Please enter correct details and try again.';
            if (!$request->has('account_number') || empty($request->get('account_number'))) {
                $response = ['status' => $status, 'message' => $defaultMessage, 'code' => 'CFE00455'];
            } elseif (!$request->has('mobile_number') || empty($request->get('mobile_number'))) {
                $response = ['status' => $status, 'message' => $defaultMessage, 'code' => 'CFE00454'];
            }

            if (empty($message)) {

                $invoice = ProFormaInvoice::where('loan_application_no', $request->get('account_number'))->first(['application_id']);
                if (isset($invoice->application_id)) {
                    $application = ConsumerApplication::where('id', $invoice->application_id)->where('mobile_number', $request->get('mobile_number'))->whereNull('is_deleted')->first(['id', 'name', 'state']);
                    if (isset($application->id) && $request->has('txn_id')) {

                        $paymentTransaction = PaymentTransaction::where('trasanction_id', $request->get('txn_id'))->whereNull('is_deleted_at')->first(['id']);
                        if (!isset($paymentTransaction->id)) {

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


                            if (isset($payment[$application->id]) && isset($payment[$application->id]['amount_due']) && $payment[$application->id]['amount_due']) {
                                $min = $payment[$application->id]['amount_due'];
                                $max = $payment[$application->id]['amount_pending'];
                                if ($request->get('amount') >= $min && $request->get('amount') <= $max) {

                                    $PaymentEmi = new LoanManagement();

                                    $paymentUpdate = $PaymentEmi->paymentReconcile([
                                        'mode' => 'Paytm',
                                        'paid_by' => '',
                                        'application_id' => $application->id,
                                        'bank_id' => (new ConsumerApplicationController())->getTransactionBank($application->id),
                                        'umrn' => '',
                                        'collected_by' => 107,
                                        'trasanction_id' => $request->get('txn_id'),
                                        'wallet_name' => '',
                                        'payment_date' => date('Y-m-d'),
                                        'amount' => $request->get('amount'),
                                        'status' => $request->get('payment_status'),
                                        'reason' => '',
                                        'trasanction_acknowledgement' => '',
                                        'online_payment_id' => '']);

                                    if ($paymentUpdate && isset($paymentUpdate['cf_transaction_id'])) {
                                        $status = 'OK';
                                        $response = ['status' => $status, 'message' => 'Thanks for your payment of Rs ' . $request->get('amount') . ' for your loan ID ' . $request->get('account_number') . ' on ' . date('Y-m-d') . ' with transaction ID ' . $paymentUpdate['cf_transaction_id'] . '.', 'code' => 'OK']; //CFE00452 code not handled because from paytm side module is in UAT.
                                    } else {
                                        $response = ['status' => $status, 'message' => 'We can\'t handle this request. Please try again later', 'code' => 'CFE00501'];
                                    }
                                } else {
                                    $response = ['status' => $status, 'message' => 'Amount should be greater than ' . $min . ' and less than ' . $max, 'code' => 'CFE00456'];
                                }
                            } else {
                                $message = 'There are no pending dues for the details';
                                $response = ['status' => $status, 'message' => $message, 'code' => 'CFE00453'];
                            }
                        }else{
                            $message = 'Transaction mismatch';
                            $response = ['status' => $status, 'message' => $message, 'code' => 'CFE00457'];
                        }

                    } else {
                        $response = ['status' => $status, 'message' => $defaultMessage, 'code' => 'CFE00454'];
                    }
                } else {
                    $response = ['status' => $status, 'message' => $defaultMessage, 'code' => 'CFE00455'];
                }
            }
        }catch (\Exception $e){
            $message = 'Couldn\'t connect to the server. Please try again later.';
            $response = ['status' => $status, 'message' => $message, 'code' => 'CFE00501'];
        }

        return response()->json($response);
    }


    public function generateCallbackRequest(Request $request){

        (new \App\Slack(new Request(['title'=>'User Requested Callback',
            'fields'=>['Mobile Number'=>$request->get('phone')], 'group' => 'businessdevelopment'])))->send();

        $data['status']  = 'OK';
        $data['message'] = 'We will get in touch shortly';
        return response()->json($data);
    }
    public function recordContactFormDetails(Request $request){

        $contactDetails = [];
        foreach($request->all() as $key=>$item){
            $contactDetails = array_merge($contactDetails, [$key => $item]);
        }

        if($contactDetails['Department']=== 'sales'){
            $to = 'bd@creditfair.in';
        } else if($contactDetails['Department']=== 'payments'){
            $to = 'payment@creditfair.in';
        } else if($contactDetails['Department']=== 'tech'){
            $to = 'tech@creditfair.in';
        } else{
            $to = 'ops@creditfair.in';
        }

        if($contactDetails) {
            Mail::send('emails.contact_form', ['contactDetails' => $contactDetails], function ($m) use ($contactDetails, $to) {
                $m->from('info@creditfair.in', 'New enquiry');
                $m->to($to)->subject('New enquiry regarding - ' . $contactDetails['Subject']);
            });

            (new \App\Slack(new Request(['title' => 'User contacted from Website',
                'fields' => $contactDetails, 'group' => 'businessdevelopment'])))->send();
        }

        $data['status']  = 'OK';
        $data['message'] = 'We will get in touch shortly';
        return response()->json($data);
    }
    public function jobApplicationForm(Request $request){
        // print_r($_POST);
        // die;
        $fields = [];
        $to='';
        $cc='';
        foreach($request->all() as $key=>$item){
            $fields = array_merge($fields, [$key => $item]);
        }
        $document = isset($fields['Resume']) ? $fields['Resume'] : '';
        $resume  = (isset($fields['First_Name']) ? $fields['First_Name'] : 'resume') . '.' . $document->getClientOriginalExtension();
        $firstName = isset($fields['First_Name']) ? $fields['First_Name'] : '';

        $to = 'careers@creditfair.in';

        Mail::send('emails.job_application', ['fields' => $fields ], function ($m) use ($document, $resume, $fields, $to) {
            $m->from('info@creditfair.in', 'Job Application');
            $m->to($to)->subject('Job Application - '.$fields['Position']);
            //$m->cc($cc);
            $m->attach($document, ['as' => $resume]);
        });

        // (new \App\Slack(new Request(['title'=>'Job Application from Website',
        //     'fields'=>$slack_data, 'group' => Slack::$HR])))->send();

        $data['status']  = 'OK';
        $data['message'] = 'We will get in touch shortly';
        return response()->json($data);
    }

    public function sendSlackNotification(Request $request){

        $type = $request->get('type');
        $id = $request->get('id');
        $consumer = ConsumerApplication::where('id', $id)->where('state','approved')->whereNull('is_deleted')->first(['id','name','created_by','user_id','state']);
        $advisor_id = $consumer->created_by ?? '';
        $user = User::where('id', $advisor_id)->first(['slack_url']);
        $slack_url = $user->slack_url ?? '';
        $segment = User::where('id', $advisor_id)->first(['id', 'name', 'slack_id']);

        if($type === 'merchant'){
            $merchant = Merchant::where('id', $id)->first();
            $fields = ['Name' => $merchant->owner_name, 'Merchant Name' => $merchant->merchant_name];
        }else{
            $application = ConsumerApplication::with('merchant')->where('id', $id)->first();
            $fields = ['Name' => $application->name, 'Merchant Name' => $application->merchant->merchant_name];
        }
        (new \App\Slack(new Request(['title'=>'Loan agreement e-sign failed - '.ucfirst($type), 'fields'=>$fields, 'group' => 'loan_application','tagging' => [$advisor_id]])))->send();
        (new \App\Slack(new Request(['title'=>'Loan agreement e-sign failed - '.ucfirst($type), 'fields'=>$fields, 'group' => $slack_url])))->send();
        $data['status'] = 'success';
        return response()->json($data);
    }

    public function saveKYC(Request $request){
        try {

            if($request->get('image_aadhaar') && $request->get('image_pan') && $request->get('image_selfie') && $request->get('application_id')){
                $user = $request->has('user') ? $request->get('user') : 'Applicant';
                $applicant_type = 1;
                $aadhar_filename = 'self_attested_aadhar';
                $pan_filename = 'self_attested_pan';
                $selfie_filename = 'self_attested_selfie';
                if($user == 'Co-Applicant'){
                    $aadhar_filename = 'self_attested_co_aadhar';
                    $pan_filename = 'self_attested_co_pan';
                    $selfie_filename = 'self_attested_co_selfie';
                    $applicant_type = 2;
                }
                $hashids = new Hashids('Creditfair by CS', 20);
                $hashed_id = $hashids->encode($request->get('application_id'));
                if($request->has('image_aadhaar')){
                    $this->getUploadCustomerMedia($request->get('image_aadhaar'), $request->get('application_id'), $aadhar_filename, $applicant_type);
                }
                if($request->has('image_pan')){
                    $this->getUploadCustomerMedia($request->get('image_pan'), $request->get('application_id'), $pan_filename, $applicant_type);
                }
                if($request->has('image_selfie')){
                    $this->getUploadCustomerMedia($request->get('image_selfie'), $request->get('application_id'), $selfie_filename, $applicant_type);
                }

                $data['status']  = 'OK';
                $data['link'] = 'esign/'.$hashed_id;
                return response()->json($data, 200);
            }
            
            $data['status']  = 'FAIL';
            $data['message'] = 'Please try after some time.';
            return response()->json($data, 200);
        } catch (\Exception $e) {
            $cwFactory = new CloudWatchLoggerFactory();
            $cwFactory->logger(json_encode(['message' => $e->getMessage(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString()]));
            $data['status']  = 'FAIL';
            $data['message'] = 'Please try after some time.';
            return response()->json($data, 200);
        }
    }

    public function saveOnfidoTries(Request $request){
        $applicant_type =  $request->get('user');
        if($request->has('application_id')){
            $element = ConsumerApplicationElement::where('application_id', $request->get('application_id'))->first(['id']);
            if (isset($element->id)) {
                $applicationElement = ConsumerApplicationElement::find($element->id);
            } else {
                $applicationElement = new ConsumerApplicationElement();
            }
            if($applicant_type === 'Applicant'){
                $applicationElement->onfido_skip = 1;
            }else{
                $applicationElement->co_app_onfido_skip = 1;
            }

            $applicationElement->save();

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

        $data['status']  = 'FAIL';
        $data['message'] = 'Failed to skip';
        return response()->json($data);
    }

    public function onfidoCheck($applicant_token){
        $payload = [
            "applicant_id" => $applicant_token,
            "report_names" => [
                "document", "facial_similarity_photo", "facial_similarity_video"
            ]
        ];
        return (new OnfidoIntegration())->createCheck($payload);
    }

    public function getOnfidoStatus(Request $request){

        try{
            $requestData =  $request->all();

            $resource_type = $requestData['payload']['resource_type'];
            if(isset($resource_type) && $resource_type == 'check'){
                $id = $requestData['payload']['object']['id'];
                $response = OnfidoIntegration::where('check_id', $id)->first(['id','application_id','check_id', 'webhook_response', 'applicant_type']);
            }else if(isset($resource_type) && $resource_type == 'report'){
                $href = explode ("/", $requestData['payload']['object']['href']);
                $id = $href[5];
                $action = $requestData['payload']['action'];
                $response = OnfidoIntegration::where('check_id', $id)->first(['id','application_id','check_id', 'webhook_response', 'applicant_type']);
            }

            if(isset($response) && isset($response->id) && !$response->webhook_response && $response->application_id && $response->applicant_type){
                OnfidoIntegration::where('check_id', $response->check_id)->update([
                    'webhook_response' => json_encode($requestData),
                ]);
                if($response->applicant_type && (isset($action) && $action == 'report.completed')) {
                    $this->runOnfidoViaJob($response->application_id, $response->applicant_type);
                }
            }
        }catch (\Exception $e){
            (new \App\Slack(new Request(['title'=>'Onfido Catch', 'fields'=>['value' => $e->getMessage()]])))->send();
        }

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

    public function runOnfidoViaJob($application_id, $applicant_type){
        $run_onfido = CampaignsJobProvider::where('from','run_onfido')->where('application_id', $application_id)->where('applicant_type', $applicant_type)->where('is_available',0)->first(['id','applicant_type']);
        if(!isset($run_onfido->id) && $applicant_type > 0) {
            $jobs = new CampaignsJobProvider();
            $jobs->from = 'run_onfido';
            $jobs->payload = json_encode(['id' => $application_id]);
            $jobs->available_at = Carbon::now()->addMinute(5)->toDateTimeString();
            $jobs->application_id = $application_id;
            $jobs->created_at = Carbon::now()->toDateTimeString();
            $jobs->is_available = 0;
            $jobs->applicant_type = $applicant_type;
            $jobs->save();
        }else if (!$run_onfido->applicant_type){
            CampaignsJobProvider::where('id',$run_onfido->id)->update(['applicant_type' => $applicant_type]);
        }
    }

    public function checkStatusLogin(){
        $mp = Input::get('mp');
        $token = Input::get('_token');
        if($this->isSystemByPass || csrf_token() == $token) {
            $user = User::where('mobile_number', $mp)->where('user_type', '>=', 5)->first(['id','admin_login_counter','deleted_at']);
            if(isset($user->id) && !$user->deleted_at) {
                if (isset($user->id) && $user->admin_login_counter >= 3) {
                    return response()->json(['status' => 'FAIL', 'error' => 'Account locked. Contact site admin']);
                }
                if (isset($user->id)) {
                    $this->generateOtp(new Request(['mobile_number' => $mp, 'isResend' => 1, 'isEmail' => 1]));
                    return response()->json(['status' => 'OK']);
                }
            }
        }

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

    public function checkStatusLoginVerify_MS(){
        $tkn = '/admin/otp/login/?cknt=' . Input::get('cknt') . '&ckn=' . Input::get('ckn');
        return response()->json(['status' => 'OK', 'tkn' => $tkn]);
    }

    public function checkStatusLoginVerify(){
        $otp = Input::get('otp');
        $mp = Input::get('mp');
        $token = Input::get('_token');
        if(csrf_token() == $token) {
            $user = User::where('mobile_number', $mp)->where('user_type', '>=', 5)->first(['id','admin_login_counter','deleted_at']);
            if(isset($user->id) && !$user->deleted_at) {
                if (isset($user->admin_login_counter) && $user->admin_login_counter >= 3) {
                    return response()->json(['status' => 'FAIL', 'error' => 'Account locked. Contact site admin']);
                }
                if (isset($user->id)) {
                    $response = $this->verifyOtp(new Request(['mobile_number' => $mp, 'otp' => $otp]));
                    if ($response->getData()->message == 'OTP successfully verified') {

                        $hashids = new Hashids('Creditfair by CS', 20);
                        $hashid = $hashids->encode($user->id);
                        $hashidTime = $hashids->encode(Carbon::now()->addSecond(10)->timestamp);
                        User::where('id', $user->id)->where('user_type', '>=', 5)->update(['admin_login_counter' => 0]);
                        return response()->json(['status' => 'OK', 'tkn' => '/admin/otp/login/?cknt=' . csrf_token() . '&ckn=' . $hashid . '|' . $hashidTime]);
                    } else {
                        if (isset($user->admin_login_counter) && $user->admin_login_counter >= 3) {
                            return response()->json(['status' => 'FAIL', 'error' => 'Account locked. Contact site admin']);
                        }
                        User::where('id', $user->id)->where('user_type', '>=', 5)->update(['admin_login_counter' => DB::raw('admin_login_counter+1')]);
                        AdminLoginLogs::insert([
                            'user_id' => $user->id,
                            'ip' => $this->get_client_ip(),
                            'created_at' => Carbon::now()->toDateTimeString()
                        ]);
                    }
                }
            }
        }

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

//    public function getFinboxStatus(Request $request){
//        $requestData =  $request->all();
//
//        $request_id = (string)$requestData['request_id'];
//        $customer_id = (string)$requestData['customer_id'];
//
//        $salt = base64_encode(hex2bin(hash('sha256', (strtoupper(md5($customer_id)).(_env('FINBOX_WEBHOOK_SECRET', ''))))));
//
//        if($requestData['salt'] === $salt){
//            (new \App\Slack(new Request(['title'=>'FinBox Webhook - Incoming ', 'fields'=>['value' => json_encode($requestData)]])))->send();
//            (new finBoxIntegration())->getWebHookResponse($customer_id ,$request_id);
//        }
//    }

    private function validateMobileNumber($data) {
        return \Validator::make($data,[
            'mobile_number' => 'required|regex:/^([6-9]{1})([0-9]{9,11})$/',
        ]);
    }

    public function addCancellationDetails(Request $request)
    {
        $paymentTransaction = new PaymentTransaction();
        $paymentTransaction->fill($request->input());
        $paymentTransaction->status = "success";
        $paymentTransaction->emi_payment_id = 0;
        $paymentTransaction->payment_date = $request->received_date;
        $paymentTransaction->payment_reconciliation_date = $request->received_date;
        $paymentTransaction->payment_for = "cancellation_charges";
        if ($paymentTransaction->save()) {
            return response()->json(['status' => 'OK', 'message' => 'Cancellation Details Submitted']);
        }
        return response()->json(['status' => 'FAIL', 'message' => 'Something went wrong']);
    }

    public function updateUtkarshVKYC(Request $request){
        if ($request->has('application_id')){
            $hashids = new Hashids('Creditfair by CS', 20);
            if($request->has('hashed_id')) {
                $id = $hashids->decode($request->get('hashed_id'));
                $id = $id[0];
                $applicant_type = $hashids->decode($request->get('applicant_type'));
                $applicant_type = $applicant_type[0];
            }else{
                $id = $request->get('application_id');
                $applicant_type = $request->get('applicant_type');
            }

            $utkarsh = new Utkarsh(new Request(['application_id' => $id, 'applicant_type' => $applicant_type]));
            $kycResponse = $utkarsh->getKYCDetailsLink();
            return response()->json(['status' => 'OK', 'kycResponse' => $kycResponse], 200);
        }
        return response()->json(['status' => 'FAIL'], 200);
    }

    public function initiateKYCService($hash_id, $applicant_type_hashed){
        if($hash_id) {
            $hashids = new Hashids('Creditfair by CS', 20);
            $hashed_id = $hashids->decode($hash_id);
            $applicant_type = $hashids->decode($applicant_type_hashed);
            if(isset($hashed_id[0])) {
                $utkarshKYCData = UtkarshKYCData::where('application_id', $hashed_id[0])->where('applicant_type', $applicant_type[0])->whereNotNull('response_data')->orderBy('created_at', 'desc')->first(['id']);
                if(isset($utkarshKYCData->id)){
                    $request = new Request(['kyc_link_only' => 1, 'applicant_type' => $applicant_type[0]]);
                    $response = (new ConsumerApplicationController())->sendUtkarshKYC($request, $hashed_id[0]);
                    $res = $response->getData();
                    if (isset($res->status) && $res->status == 'OK' && isset($res->url) && $res->url){
                        return \redirect()->to($res->url);
                    }
                }
                $application = ConsumerApplication::where('id', $hashed_id[0])->first(['id']);
                if(isset($application->id)) {
                    return view('front.customer_kyc', ['hashed_id' => $hashed_id[0], 'applicant_type' => $applicant_type[0]]);
                }
            }
        }
        abort(404);
    }

    public function initiateCustomerKYC(Request $request){
        $request->merge(['id' => $request->get('ref_id'), 'application_id' => $request->get('ref_id')]);
        $utkarsh_otp_generate = (new Utkarsh($request))->generateOTP();
        return response()->json(['status' => 'OK', 'data' => []]);
    }

    public function validateCustomerKYC(Request $request){
        $request->merge(['id' => $request->get('ref_id'), 'application_id' => $request->get('ref_id'), 'applicant_type' => $request->get('applicant_type')]);
        $utkarsh_otp_valiate = (new Utkarsh($request))->OTPVerification();
        $request->merge(['kyc_link_only' => 1]);
        $response = (new ConsumerApplicationController())->sendUtkarshKYC($request, $request->get('ref_id'));
        $res = $response->getData();
        if (isset($res->status) && $res->status == 'OK' && isset($res->url) && $res->url){
            return response()->json(['status' => 'OK', 'data' => [], 'url' => $res->url]);
        }
        return $res;
    }

    public function getLenderData(Request $request){
        $lenders = Lenders::get(['id as lender_id', 'name as lender_name']);

        return response()->json($lenders, 200);
    }

    public function getApplicationData(Request $request){
        $source = $request->get('source');
        foreach($source as $index => $source_item){
            //$table[$item['table']][] = $item;
            $column = $source_item['column'];
            $table_name = $source_item['table'];
            if($request->get('identifier_id') > 0) {
                $table_attributes = $this->getTableMapping($table_name);
                if (Schema::hasColumn($table_attributes['table'], $column)) {
                    $application = $table_name::where($table_attributes['foreign_column'], $request->get('identifier_id'))->select([$column])->get();
                    foreach ($application as $item) {
                        $source[$index]['value'] = $item->$column;
                    }
                } else {
                    $source[$index]['value'] = null;
                }
            }else{
                $source[$index]['value'] = null;
            }
        }

        return response()->json($source, 200);
    }

    public function getTableMapping($map){
        $mapping = [
            "App\\ConsumerApplication" => ['table' => 'consumer_application', 'foreign_column' => 'id'],
            "App\\ConsumerApplicationElement" => ['table' => 'consumer_application_element', 'foreign_column' => 'application_id'],
        ];

        return $mapping[$map];
    }

    public function triggerEbillOcr($applicationId, $filePath)
    {
        try {
            $fileContent = Storage::disk('s3')->get($filePath);
            $base64Content = base64_encode($fileContent);
            $filename = basename($filePath);

            $payload = json_encode([
                'id'       => $applicationId,
                'content'  => $base64Content,
                'filename' => $filename,
            ]);

            $curl = curl_init();
            curl_setopt_array($curl, [
                CURLOPT_URL            => _env('OCR_WORKFLOW_ENGINE_URL'),
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT        => 30,
                CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST  => 'POST',
                CURLOPT_POSTFIELDS     => $payload,
                CURLOPT_HTTPHEADER     => [
                    'Content-Type: application/json',
                ],
            ]);

            $response = curl_exec($curl); // "{"success":true,"executionId":"f076764e-26df-4361-99fc-5fe00238edbf","status":"Success","message":"Webhook processed successfully","workflow":"E-bill OCR","timestamp":"2026-08-20T07:02:52.285Z"}"
            $error    = curl_error($curl);
            curl_close($curl);


            $validation = UtilityValidation::where('consumer_application_id', $applicationId)->first(['id']);

            if(!isset($validation->id)){
                $file = ConsumerApplicationFiles::where('consumer_application_id', $applicationId)->where('file_path', $filePath)->whereNull('deleted_at')->first(['id', 'customer_id']);
                $application = ConsumerApplication::with('application_element')->where('id', $applicationId)->first(['id', 'mobile_number', 'name', 'co_applicant_name', 'state', 'merchant_id']);
                if(isset($file->id)){

                    $customer_id = $file->customer_id;
                    $ebill_ocr_data = DB::selectOne('SELECT consumer_number, consumer_name, discom_name FROM ebill_ocr_data WHERE application_id = ? AND consumer_number IS NOT NULL LIMIT 1',[$applicationId]);
                    if(isset($ebill_ocr_data->consumer_number) && $ebill_ocr_data->consumer_number){
                        $customer_id = $ebill_ocr_data->consumer_number;
                        ConsumerApplicationFiles::where('id', $file->id)->update(['discom_mobile' => $application->mobile_number, 'discom_district' => $application->application_element->discom_district, 'customer_id' => $customer_id, 'provider' => $application->application_element->discom_service_provider]);
                    }

                    if (in_array($application->state, ['form completed', 'in-process', 'waiting for decision'])) {
                        // Name match based on OCR data
                        $matcher = new NameMatchService();
                        $score = $matcher->nameMatch(strtolower($application->name), strtolower($ebill_ocr_data->consumer_name));
                        $applicantNamePercentage = is_numeric($score) ? round($score, 2) : 0;
                        $resultArray['applicant_match'] = round($applicantNamePercentage);
                        if (!empty($application->co_applicant_name)) {
                            $coAppscore = $matcher->nameMatch(strtolower($application->co_applicant_name), strtolower($ebill_ocr_data->consumer_name));
                            $coApplicantNamePercentage = is_numeric($coAppscore) ? round($coAppscore, 2) : 0;
                            $resultArray['co_applicant_match'] = round($coApplicantNamePercentage);
                        }
                        ConsumerApplicationFiles::where('id', $file->id)->update(['ebill_name_verify' => json_encode($resultArray)]);
                        // re-run BRE for applicant
                    //     $applicant_type = 1;
                    //     Input::merge(['applicant_type' => 1]);  // Added here to overwrite the value set in input for hard pull of co-applicant
                    //     $consumerApplicationController = new ConsumerApplicationController();
                    //     $response = $consumerApplicationController->generateSoftBureauReport($applicationId, 'autoBRE', 1, true);
                    //     $responseData = $response->getData();
                    //     if ($responseData->status == 'OK' && !$responseData->is_rejected && !$responseData->is_pre_approved) { // Dont change status in case, application is rejected or pre approved
                    //         if (isset($responseData->is_approved) && $responseData->is_approved) {
                    //             $status = 'approved';
                    //             if ($consumerApplicationController->isMultiLender($application->merchant_id) > 1) {
                    //                 $status = 'cf approved';
                    //             }
                    //         } else if (isset($responseData->is_approved) && !$responseData->is_approved) {
                    //             $status = 'waiting for decision';
                    //         }
                    //         if ($status != $application->state) {
                    //             \request()->merge(['state' => $status, 'autoDecisionQueue' => true]);
                    //             $consumerApplicationController->updateStatus($applicationId, true);
                    //         }
                    //     }
                    }
                    (new ConsumerApplicationController())->getUtilityBillValidation(new Request(['application_id' => $applicationId,'customer_id' => $customer_id, 'provider' => $application->application_element->discom_service_provider, 'district' => $application->application_element->discom_district, 'mobile_number' => $application->mobile_number]));
                }
            }

            $cwFactory = new CloudWatchLoggerFactory();
            $cwFactory->logger(json_encode([
                'application_id' => $applicationId,
                'vendor'         => 'workflow_engine',
                'api_name'       => 'ebill_ocr',
                'api_url'        => _env('OCR_WORKFLOW_ENGINE_URL'),
                'file_path'      => $filePath,
                'response'       => json_decode($response),
                'error'          => $error,
            ]));
        } catch (\Exception $e) {
            $cwFactory = new CloudWatchLoggerFactory();
            $cwFactory->logger(json_encode(['message' => $e->getMessage(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString()]));
        }
    }
}

