<?php

namespace App\Http\Controllers;

use App\_Slack;
use App\ABFL\Services\Services;
use App\ApplicationEMICalculation;
use App\Bank;
use App\CampaignTracking;
use App\Careers;
use App\Comments;
use App\ConsumerApplication;
use App\ConsumerApplicationElement;
use App\Customers;
use App\Http\Controllers\Admin\RepaymentController;
use App\MerchantCategoryKYCRules;
use App\Departments;
use App\DigitalSignDetails;
use App\Dump;
use App\ekycIntegration;
use App\EMICalculation;
use App\EmiPayment;
use App\FinBit;
use App\Singularity\Singularity;
use App\JMService\JMServices;
use App\ForeclosureBreakup;
use App\JobProvider;
use App\Logging\CloudWatchLoggerFactory;
use App\OneFinService;
use App\RPS_Logs;
use App\UserGeolocation;
use App\Utkarsh\Utkarsh;
use App\Vivriti;
use Illuminate\Support\Facades\DB;
use Razorpay\Api\Api;
use App\Http\Controllers\Admin\AccountingController;
use App\Http\Controllers\Admin\ConsumerApplicationController;
use App\Http\Controllers\Admin\ConsumerDocument;
use App\Http\Controllers\Admin\DisbursementController;
use App\Http\Controllers\TestScripts\TestScripts;
use App\Http\Middleware\MongoMiddleware;
use App\HypervergeVideo;
use App\HypervergeVideoAttribute;
use App\HypervergeWebhook;
use App\Jobs;
use App\KYCDetails;
use App\LendBox;
use App\LendBoxLSP;
use App\LenderLanguageConsent;
use App\Lenders;
use App\LoanManagement;
use App\Mandate;
use App\Merchant;
use App\MerchantCategory;
use App\MerchantFiles;
use App\MerchantLocation;
use App\MerchantModule;
use App\MerchantOffers;
use App\OnfidoIntegration;
use App\OnlinePayment;
use App\OtpManager;
use App\Partners;
use App\PaymentEmi;
use App\PaymentTransaction;
use App\PayoutCF\CF_Logs;
use App\ProFormaInvoice;
use App\SanctionAmountLogs;
use App\Slack;
use App\StateModel;
use App\StaticPage;
use App\TelecomDetails;
use App\Templates;
use App\User;
use App\WebSEO;
use Carbon\Carbon;
use function Composer\Autoload\includeFile;
use Hashids\Hashids;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Input;
use App\ConsumerApplicationFiles;
use Illuminate\Support\Facades\App;
use Aws\S3\Exception\S3Exception;
use Aws\S3\S3Client;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\URL;
use App\Model\LoanAgreementVendor;
use App\KarzaVideo;
use App\KarzaVideoAttribute;
use App\KarzaVideoWebhook;
use App\Avanse\Services\AvanseServices;
use App\KMGP2P;
use App\LoanHypothecation\LoanHypothecation;
use App\Shortio;
use App\DigioVKYC;
use App\BankValidation;

class FrontController extends Controller
{
    public $state = [];
    public $isInternal = false;

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

    public function getApplication(Request $request)
    {

        $referrer = $_SERVER['HTTP_REFERER'] ?? "Unknown";
        if($referrer == "https://pmsuryaghar.gov.in/"){
            return \redirect()->to('https://solar.creditfair.in/onboarding');
        }

        //return \redirect()->to('application/mypat?data=bGtzZGFzZnNhc2tsbG9wbIGYMoxaw+NU26Ay9oQjZJVzfOTtcsYoYGYajUf5Tm8PFG9t5Nb+GeMLr4+v7r74ze/W4tLiMWWV9R2WuClSOcGGLeKxsPBkuuKmKRnLf5GfJ9QViPrwYgo9oWOuDlVJPUSfoN+iAJaq5vrrWin98X7uE20vnYwf2I8gaVuGZUnIQOaSrGq8dygU17JgE2vHQA==');
        $merchant_id = $this->getMerchantHash();
        $merchant_slug = (Input::has('txn')) ? (Input::get('txn')): " " ;
        if($merchant_id > 0 || $merchant_slug != ""){
            $merchant = Merchant::with('offer')->where('id',$merchant_id)->orWhere('slug',$merchant_slug)->first();
            if(isset($merchant->id)) {
                $merchant_id = $merchant->id;
                if (isset($merchant->category_id)) {
                    $data['merchant_details'] = Merchant::where('status', 'active')->where('id', $merchant_id)->get();
                    $data['selectedMerchantCategoryID'] = $merchant->category_id;
                    $data['selectedMerchantOffers'] = $merchant->offer;
                    $data['selectedMerchant'] = $merchant;
                }
            }
        }

        $data['seo_data'] = $this->getSEOData();

        $data['docs'] = true;
        $data['states'] = $this->state;
        $data['merchant_list'] = Merchant::where('status','active')->where('receive_application', 1)->get(['merchant_name as name','id']);
        $data['merchant_category'] = MerchantCategory::where('status',1)->where('receive_application', 1)->get(['name','id']);
        $data['selectedMerchantID'] = $merchant_id;
        $data['selectedMerchantIDCat'] = (isset($data['selectedMerchantCategoryID'])) ? $data['selectedMerchantCategoryID'] : 0;
        $data['inverter_list'] = (new ConsumerApplicationController())->inverterList();
        $data['panel_list'] = (new ConsumerApplicationController())->panelList();

        if ($request->has('data') && !empty($request->get('data')) && $merchant_id) {
            $data = $this->initAutomation($request, $data, $merchant_id);
        }

        return view('front.application.application', $data);
    }

    public function getMerchantHash(){
        if(Input::has('txn') && !empty(Input::get('txn'))) {
            $hashids = new Hashids('Creditfair by CS', 20);
            $id =  $hashids->decode(Input::get('txn'));
            if (isset($id[0])){
                return $id[0];
            }
            return 0;
        }
        return 0;
    }

    public function getSEOData(){
        $route = \Illuminate\Support\Facades\Route::getRoutes()->match(request());
        return WebSEO::where('url', request()->path())->first();
    }

    public function getHomePage(){
        $data = array();
        $data['is_home'] = true;
        $data['seo_data'] = $this->getSEOData();
        $staticPage = StaticPage::where('web_notice',1)->first();
        if (isset($staticPage->html)){
            $message = str_replace('Guidelines on Moratorium:', '', strip_tags($staticPage->html));
            $data['modal_message'] = substr($message, 0, 135);
            $data['modal_title'] = $staticPage->title;
            $data['modal_url'] = 'page/'.$staticPage->url;
        }
        return view('homepage_v2', $data);
    }

    public function getProductPage($product, $city = null){
        $data = array();
        // $data['is_home'] = true;
        $data['seo_data'] = $this->getSEOData();
        // $staticPage = StaticPage::where('web_notice',1)->first();
        // if (isset($staticPage->html)){
        //     $message = str_replace('Guidelines on Moratorium:', '', strip_tags($staticPage->html));
        //     $data['modal_message'] = substr($message, 0, 135);
        //     $data['modal_title'] = $staticPage->title;
        //     $data['modal_url'] = 'page/'.$staticPage->url;
        // }
    $cityFromSession = session('selected_city');
    $previousProduct = session('previous_product');

    if ($city) {
        session(['selected_city' => $city]);
    }

    $justSwitchedProduct = false;
    if ($previousProduct && $previousProduct !== $product) {
        session()->flash('just_switched_product', true);
        $justSwitchedProduct = true;
    }
    session(['previous_product' => $product]);

    $referer = request()->headers->get('referer');
    $isManualVisit = !$referer || !str_contains($referer, '/products/');

    if (
        !$city &&
        $cityFromSession &&
        !request()->has('no_city') &&
        ($justSwitchedProduct || !$isManualVisit)
    ) {
        return redirect("/products/{$product}/{$cityFromSession}");
    }
        $faqs = [
            'residential' => [
                [
                    'question' => 'What documentation is required for solar financing?',
                    'answer' => 'To apply for a solar loan, you typically need: <ul><li>KYC Documents (Aadhaar, PAN)</li><li>Electricity Bill</li></ul>Our fully digital process ensures you can upload these documents online for a seamless experience.',
                ],
                [
                    'question' => 'Who is eligible for solar financing?',
                    'answer' => 'Homeowners across India are eligible to apply. Additionally, any earning blood relative of the owner can apply on their behalf.',
                ],
                [
                    'question' => 'What are the interest rates?',
                    'answer' => 'We offer competitive interest rates to make solar affordable for everyone.',
                ],
                [
                    'question' => 'What is repayment tenure?',
                    'answer' => 'You can choose flexible repayment terms ranging from 6 to 60 months.',
                ],
                [
                    'question' => 'What does solar insurance cover?',
                    'answer' => 'Solar insurance covers damages caused by fire, lightning, explosions, storms, cyclones, floods, earthquakes, and other natural calamities as per the Standard Fire and Special Perils Policy. It also includes protection against burglary, housebreaking, and damages from incidents like riots, strikes, and impact or water-related accidents.',
                ],
            ],
            'msme' => [
                [
                    'question' => 'What businesses are eligible for MSME & rural solar financing?',
                    'answer' => 'Any small or medium enterprise, shop, or rural business looking to reduce energy costs can apply. We consider all types of business constitutions like proprietorship, partnership, trust, LLP, and private limited companies.',
                ],
                [
                    'question' => 'What documents are required?',
                    'answer' => '<ul><li>Business registration proof (As applicable)</li><li>Owner’s ID proof (Aadhaar, PAN, etc.)</li><li>Electricity Bill</li><li>Income proof (Bank statements or ITR)</li></ul>',
                ],
                [
                    'question' => 'What are the interest rates?',
                    'answer' => 'We offer competitive interest rates to make solar affordable for everyone.',
                ],
                [
                    'question' => 'What is repayment tenure?',
                    'answer' => 'Flexible tenures ranging from 6 to 60 months, designed for business needs.',
                ],
                [
                    'question' => 'What does solar insurance cover?',
                    'answer' => 'Solar insurance covers damages caused by fire, lightning, explosions, storms, cyclones, floods, earthquakes, and other natural calamities as per the Standard Fire and Special Perils Policy. It also includes protection against burglary, housebreaking, and damages from incidents like riots, strikes, and impact or water-related accidents.',
                ],
            ],
            'housing' => [
                [
                    'question' => 'Is solar financing available for individual apartments or only for common areas?',
                    'answer' => 'Financing is available for both common areas (like streetlights, parking, etc.) and individual apartment units.',
                ],
                [
                    'question' => 'What documents are required?',
                    'answer' => '<ul><li>Society Registration Certificate/Deed</li><li>List of Members</li><li>Occupancy Certificate/Conveyance Deed</li><li>Audited Financials (last 2 years)</li><li>Bank Statements (12 months)</li><li>Quotation for Solar Installation</li><li>Copy of Bye-laws</li><li>EGM/AGM Resolution for Solar and Borrowing</li><li>Latest 3 Months E-bill for All Meters</li><li>Bureau Report of Society and Key Officials (Chairman, Secretary, Treasurer)</li></ul>',
                ],
                [
                    'question' => 'What are the interest rates?',
                    'answer' => 'We offer competitive interest rates to make solar affordable for everyone.',
                ],
                [
                    'question' => 'What is repayment tenure?',
                    'answer' => 'Flexible repayment tenures of 6 to 60 months based on society\'s needs.',
                ],
                [
                    'question' => 'What does solar insurance cover?',
                    'answer' => 'Solar insurance covers damages caused by fire, lightning, explosions, storms, cyclones, floods, earthquakes, and other natural calamities as per the Standard Fire and Special Perils Policy. It also includes protection against burglary, housebreaking, and damages from incidents like riots, strikes, and impact or water-related accidents.',
                ],
            ],
        ];

        $category = request('product', 'residential'); 

        $cityFormatted = $city ? ucfirst($city) : null;

        if ($cityFormatted) {
            // Update Residential FAQs
            $faqs['residential'][0]['answer'] = "To apply for a solar loan in {$cityFormatted}, you typically need: <ul><li>KYC Documents (Aadhaar, PAN)</li><li>Electricity Bill</li></ul>Our fully digital process ensures you can upload these documents online for a seamless experience.";

            $faqs['residential'][1]['question'] = "Who is eligible for solar financing in {$cityFormatted}?";

            $faqs['residential'][2]['answer'] = "We offer competitive interest rates on solar loans in {$cityFormatted} to make solar energy affordable.";

            // Update MSME FAQs
            $faqs['msme'][1]['question'] = "What documents are required for solar loan in {$cityFormatted}?";

            $faqs['msme'][2]['answer'] = "We offer competitive interest rates for solar loans in {$cityFormatted}, making solar adoption easier for MSMEs.";

            // Update Housing FAQs
            $faqs['housing'][1]['question'] = "Documents Required for Housing Society Solar Loan in {$cityFormatted}";
        }
        $data['faqs'] = $faqs[$category] ?? [];
        $data['product'] = request('product');
        $data['city'] = $city ? ucfirst($city) : null;
        return view('products',$data);
    }

    public function getOldKYCPolicy()
    {
        $data = array();
        $data['is_home'] = true;
        return view('front.kyc-policy', $data);
    }

    public function getReferral()
    {
        $data = array();
        $data['is_home'] = true;
        return view('front.refer-earn', $data);
    }

    public function getOldFairPracticePolicy()
    {
        $data = array();
        $data['is_home'] = true;
        return view('front.fair-practice-policy', $data);
    }

    public function getApplicationbyId( Request $request, $hashed_id, $center_hashed_id = null)
    {
        $merchant = Merchant::with('offer')->where('slug', $hashed_id)->first();
        if (empty($merchant)){
            return redirect()->to('application');
        }
        else if($merchant->status == 'inactive'){
            return redirect()->to('application');
         }
        if($center_hashed_id) {
            $merchantLocation = MerchantLocation::where('slug', $center_hashed_id)->first();
        }

        //Redirect solar cases to solar form
        if(isset($merchant->category_id) && $merchant->category_id == 24) {
            $centerSlug = '';
            if($center_hashed_id){
                $centerSlug  = '&center_slug=' . $center_hashed_id;
            }
            return \redirect()->to(_env('SOLAR_FORM_HOST').'?merchant_slug=' . $hashed_id. $centerSlug);
        }

        if(isset($merchant->id)){
            $merchant_id = $merchant->id;
            if ($merchant_id > 0) {
                $merchant = Merchant::with('offer')->where('id', $merchant_id)->first();
                if (isset($merchant->category_id)) {
                    $data['merchant_details'] = Merchant::where('status', 'active')->where('id', $merchant_id)->get(['id','merchant_name']);
                    $data['selectedMerchantCategoryID'] = $merchant->category_id;
                    $data['selectedMerchantOffers'] = $merchant->offer;
                    $data['selectedMerchant'] = $merchant;
                }
            }
            if($merchant_id == 6543){
                $data['loan_amount'] = 300000;
            }
            $data['docs'] = true;
            $data['states'] = $this->state;
            $data['merchant_list'] = Merchant::where('status', 'active')->get(['merchant_name as name', 'id']);
            $data['merchant_category'] = MerchantCategory::where('status', 1)->get(['name', 'id']);
            $data['selectedMerchantID'] = $merchant_id;
            $data['selectedMerchantIDCat'] = (isset($data['selectedMerchantCategoryID'])) ? $data['selectedMerchantCategoryID'] : 0;
            $data['merchantLocation'] = isset($merchantLocation) ? $merchantLocation : '';
            if($data['merchantLocation']){
                $data['merchant_location_id'] = isset($merchantLocation->id) ? $merchantLocation->id : '';
            }
            $data['inverter_list'] = (new ConsumerApplicationController())->inverterList();
            $data['panel_list'] = (new ConsumerApplicationController())->panelList();

            if ($request->has('data') && !empty($request->get('data')) && isset($merchant->id)) {
                $data = $this->initAutomation($request, $data, $merchant->id);
            }

            return view('front.application.application', $data);
        }
        if($hashed_id == 'cellugen') {
            $merchant_id = 48;
            if ($merchant_id > 0) {
                $merchant = Merchant::with('offer')->where('id', $merchant_id)->first();
                if (isset($merchant->category_id)) {
                    $data['merchant_details'] = Merchant::where('status', 'active')->where('id', $merchant_id)->get();
                    $data['selectedMerchantCategoryID'] = $merchant->category_id;
                    $data['selectedMerchantOffers'] = $merchant->offer;
                    $data['selectedMerchant'] = $merchant;
                }
            }
            $data['docs'] = true;
            $data['states'] = $this->state;
            $data['merchant_list'] = Merchant::where('status', 'active')->get(['merchant_name as name', 'id']);
            $data['merchant_category'] = MerchantCategory::where('status', 1)->get(['name', 'id']);
            $data['selectedMerchantID'] = $merchant_id;
            $data['selectedMerchantIDCat'] = (isset($data['selectedMerchantCategoryID'])) ? $data['selectedMerchantCategoryID'] : 0;
            $data['inverter_list'] = (new ConsumerApplicationController())->inverterList();
            $data['panel_list'] = (new ConsumerApplicationController())->panelList();

            if ($request->has('data') && !empty($request->get('data')) && isset($merchant->id)) {
                $data = $this->initAutomation($request, $data, $merchant->id);
            }

            return view('front.application.application', $data);
        }
        $data = array();

        $data['states'] = $this->state;

        $hashids         = new Hashids('Creditfair by CS', 20);
        $application_ids = $hashids->decode($hashed_id);

        if (isset($application_ids[0]) && $application_ids[0]) {
            $application = \App\ConsumerApplication::find($application_ids[0]);
            if ($application) {
                $data['application'] = $application;
                if ($data['application']->additional_docs) {
                    $data['additional_docs_list'] = explode(",", $data['application']->additional_docs_list);
                }
                if ($request->input('docs')) {
                    if (($application->completed_stage == 2 && $application->co_applicant_required == 0) || $application->completed_stage == 3) {
                        $data['docs'] = true;
                    }
                }

                if((!$application->additional_docs || !isset($docs))) {
                    $comments = Comments::with('user')->where('application_id',$application->id)->where('show_merchant',1)->get();
                    $status = ($application->completed_stage == 3) ? view('front.application.view_application',['response'=>$application,'comments'=>$comments]) : false;
                    if($status)
                        return (\Auth::check() && \Auth::user()->user_type) ? $status : redirect()->intended('application/login');
                }

                $merchant_location = \App\MerchantLocation::find($application->merchant_location_id);
                if ($merchant_location) {
                    $merchant = \App\Merchant::find($merchant_location->merchant_id);
                    if ($merchant) {
                        $data['merchant_name'] = $merchant->merchant_name;
                        $data['merchant_logo'] = $merchant->merchant_logo;

                        $data['merchant_location_name'] = $merchant_location->name;
                        $data['merchant_email']         = $merchant_location->email;
                        $data['merchant_phone']         = $merchant_location->phone;
                    }
                }
            }
        } else {

            $merchant_location = \App\MerchantLocation::where('slug', $hashed_id)->first();
            if ($merchant_location) {
                $merchant = \App\Merchant::find($merchant_location->merchant_id);
                if ($merchant) {
                    $data['merchant_id']          = $merchant->id;
                    $data['merchant_location_id'] = $merchant_location->id;
                    $data['merchant_name']        = $merchant->merchant_name;
                    $data['merchant_logo']        = $merchant->merchant_logo;

                    $data['merchant_location_name'] = $merchant_location->name;
                    $data['merchant_email']         = $merchant_location->email;
                    $data['merchant_phone']         = $merchant_location->phone;
                }
            }
        }

        $data['merchant_list'] = Merchant::where('status','active')->get(['merchant_name as name','id']);
        $data['merchant_category'] = MerchantCategory::where('status',1)->get(['name','id']);

        $data['selectedMerchantIDCat'] = (isset($data['selectedMerchantCategoryID'])) ? $data['selectedMerchantCategoryID'] : 0;

        $data['inverter_list'] = (new ConsumerApplicationController())->inverterList();
        $data['panel_list'] = (new ConsumerApplicationController())->panelList();

        if ($request->has('data') && !empty($request->get('data')) && isset($merchant->id)) {
            $data = $this->initAutomation($request, $data, $merchant->id);
        }

        return view('front.application.application', $data);
    }

    public function initAutomation(Request $request, $data, $merchant_id){
        if ($request->has('data') && !empty($request->get('data')) && $merchant_id) {

            $key = '';
            if ($merchant_id == 1372 || $merchant_id == 2515){
                $key = 'genext';
            }else if($merchant_id == 2768){
                $key = 'arrivae';
            }

            if (empty($key)){
                $merchant = Merchant::with('credential')->where('id', $merchant_id)->first(['id']);
                if($merchant->credential && $merchant->credential->key){
                     $key = $merchant->credential->key;
                }
            }

            $parts = parse_url($request->getRequestUri());
            $parts = explode('data=',$parts['query']);
            if (isset($parts[1])) {
                $decrypted_string = wall_decrypt($parts[1], false, $key);
                parse_str($decrypted_string, $output);
                $data['api_init'] = true;
                $data = array_merge($data, $output);

                $this->logData($merchant_id, $data);
            }
        }

        return $data;
    }

    public function logData($merchant_id, $data){
        $cwFactory = new CloudWatchLoggerFactory();
        $data = array('merchant_id' => $merchant_id, 'vendor'=> 'BridgeAPI', 'Request'=> $data);
        $cwFactory->logger(json_encode($data));
    }


    public function coPartnerApplication($hash)
    {
        $hashids = new Hashids('Creditfair by CS', 20);
        $user_id = $hashids->decode($hash)[0];

        $user_detail = User::where('id',$user_id)->first(['merchant_id', 'center_id', 'user_type', 'name']);
        $merchant_details = Merchant::where('id', $user_detail->merchant_id)->first();
        $offer_details = MerchantOffers::where('merchant_id', $user_detail->merchant_id)->where('category_id', $merchant_details->category_id)->where('status', 1)->get();

        if($merchant_details) {
            if ($user_detail->user_type == 2) {
                $center_details = MerchantLocation::where('merchant_id', $user_detail->merchant_id)->get();
            } else {
                $center_details = MerchantLocation::where('id', $user_detail->center_id)->get();
            }

            $data['name'] = $user_detail->name;
            $data['category'] = $merchant_details->category_id;
            $data['merchant_id'] = $user_detail->merchant_id;
            $data['center_id'] = $user_detail->center_id;
            $data['centers'] = $center_details;
            $data['offers'] = $offer_details;
            return view('front.application.co-partner-application', $data);
        }
        return 'Something went wrong';
    }

    public function getApplicationLogin()
    {
        return \redirect()->to('/');
        if (\Auth::check()) {
            return redirect()->intended('application/history');
        } else {
            $data = array();
            return view('front.login', $data);
        }
    }

    public function postApplicationLogin(Request $request)
    {
        $mobile_number = $request->input('mobile_number');
        $otp           = $request->input('otp');

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

        $counter = User::where('mobile_number', $mobile_number)->first(['otp_counter','last_counter_at']);

        if ($counter) {
            $totalDuration = \Illuminate\Support\Carbon::now()->diffInSeconds($counter->last_counter_at);
            $counterInc = $counter->otp_counter ? $counter->otp_counter : 0;
            $time = $counter->last_counter_at ? $counter->last_counter_at : '';
            if ($counterInc == 3 && $totalDuration < 21600) {
                \Session::flash('error', 'Too many attempts, retry after 6 hours');
                return redirect()->back()->withInput();
            } else if ($counterInc == 3 && $totalDuration > 21600) {
                $counterInc = 1;
                $time = Carbon::now()->toDateTimeString();
            } else {
                $counterInc += 1;
                $time = Carbon::now()->toDateTimeString();
            }
            User::where('mobile_number', $mobile_number)->update(['otp_counter' => $counterInc, 'last_counter_at' => $time]);

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

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

                $user = \App\User::where('mobile_number', $mobile_number)->first(['id']);
                if ($user->id) {
                    User::where('mobile_number', $mobile_number)->update(['otp_counter' => 0, 'last_counter_at' => $time, 'user_verified'=> 1]);

                    \Auth::loginUsingId($user->id, true);
                    return redirect()->intended('application/history');
                } else {
                    \Session::flash('error', 'Mobile Number not registered');
                    return redirect()->back()->withInput();
                }
            } else {

                \Session::flash('error', 'Incorrect otp. Please try again.');
                return redirect()->back()->withInput();
            }
        }else {

            \Session::flash('error', 'Incorrect otp. Please try again.');
            return redirect()->back()->withInput();
        }
    }

    public function getUserApplications()
    {
        $applicationsTotal = 0;
        if (\Auth::check() && \Auth::user()->user_type) {
            if(\Auth::user()->user_type == 1 || \Auth::user()->user_type == 'consumer') {
                $applications = \App\ConsumerApplication::with('category','advisor')->where('mobile_number', \Auth::user()->mobile_number)->whereNull('is_deleted')->orderBy('updated_at', 'desc');
            }else{
                $applications = \App\ConsumerApplication::with('category', 'logs','advisor')->where('merchant_id', \Auth::user()->merchant_id)->whereNull('is_deleted')->orderBy('created_at', 'desc');
            }
            $applicationsTotal = $applications->get();
            $applications = $applications->paginate(10);
            $applicationObj = new ConsumerApplicationController();
            foreach ($applications as $key => &$application) {
                $hashids                = new Hashids('Creditfair by CS', 20);
                $application->hashed_id = $hashids->encode($application->id);
                $application->purpose = isset($application->category->name) ? $application->category->name : '';
                if($application->state == "disbursement checklist done"){
                    $application->state = "ready for disbursement";
                }
                if($application->state == "waiting for decision"){
                    $application->state = "in-process";
                }
                if(in_array($application->state,['form completed', 'incomplete form'])) {
                    $application->state = "new";
                }
                //$application->state = $this->getAcutalStatus($application->state, $applicationObj);
                $application->status_created_at = $this->getStatusCreatedAt($application);

            }
            $statusList =[];
            foreach ($applicationObj->arraygroup as $key=>$item){
                if(in_array($key,['form completed', 'incomplete form'])) {
                    $statusList[] = 'new';
                }elseif($key == 'disbursement checklist done'){
                    $statusList[] = 'ready for disbursement';
                }elseif($key == 'waiting for decision'){
                    $statusList[] = 'in-process';
                }else{
                    $statusList[] = $item;
                }
            }
            if(isset(Auth::user()->merchant_id)) {
                if (Auth::user()->merchant_id > 0) {
                    $data['merchant_name'] = Merchant::find(Auth::user()->merchant_id)->merchant_name;
                }else{
                    $data['merchant_name'] = '';
                }
            }
            $data['statusList'] = array_unique($statusList);
            $data['merchant_logo'] = (\Auth::user()->user_type == 'merchant') ? $this->getMerchantLogo() : '';
            $data['consumer_applications'] = $applications;
            $data['total_applications'] = ($applicationsTotal) ? count($applicationsTotal) : 0;
            return view('front.application.history', $data);
        } else {
            return redirect()->intended('application/login');
        }
    }

    public function downloadStatement($hashed_id){
        return $this->getStatementPDF($hashed_id, false);
    }

    public function getStatementPDF($hashed_id, $isPDF){
        $this->isInternal = true;$hashids = new Hashids('Creditfair by CS', 20);
        $application_ids = $hashids->decode($hashed_id);
        $bpi_case = RPS_Logs::where('application_id', $application_ids[0])->where('bpi_interest', '>', 0)->exists();
        $history = false;

        if($bpi_case){
            $history = (new RepaymentController())->getStatementDetails($application_ids[0]);
        }else{
            $history = $this->getPaymentHistory($hashed_id);
        }

        $lender = Lenders::where('id', $history['lender_id'])->first();
        $history['lender'] = $lender;
        $history['type'] = true;

        if ($history) {
//            return view('front.application.account_statement', $history)->render();
            $pdf = App::make('snappy.pdf.wrapper');
            $pdf->setTemporaryFolder(storage_path().'/')->setOption('enable-local-file-access', true);
            $statement = $pdf->loadView('front.application.account_statement', $history)->setOption('encoding', 'UTF-8')->setPaper('a4')->setOrientation('portrait');
            if ($isPDF) {
                if(!is_bool($isPDF)){
                    return $statement->inline();
                }else{
                    return $statement;
                }
                //return $statement;
            }
            return $statement->download('Account Statement.pdf');
        }

        return $history;
    }

    public function getStatement($id, $isPDF = false){
        $hashids                = new Hashids('Creditfair by CS', 20);
        $hashed_id = $hashids->encode($id);
        return $this->getStatementPDF($hashed_id, $isPDF);
    }

    public function getPaymentHistory($hashed_id){
        if (Auth::user() || $this->isInternal) {
            $hashids = new Hashids('Creditfair by CS', 20);
            $application_ids = $hashids->decode($hashed_id);

            $data = $this->getPayments($application_ids[0]);
            if ($this->isInternal)
                return $data;
            $data['selectedMerchantID'] = (isset($data['merchant_id'])) ? $data['merchant_id'] : 0;
            $data['selectedMerchantIDCat'] = (isset($data['category_id'])) ? $data['category_id'] : 0;
            return view('front.application.payment_history', $data);
        }else {
            return redirect()->intended('application/login');
        }
    }

    public function getApplicationSorted(){
        $applicationsTotal = 0;
        $_status = Input::get('sort');
        if($_status == "ready for disbursement"){
            $status = ["disbursement checklist done"];
        }elseif($_status == "in-process"){
            $status = ["in-process","waiting for decision"];
        }elseif($_status == 'new') {
            $status = ['form completed', 'incomplete form'];
        }else{
            $status = $_status;
        }

        $user = User::find(Input::get('u_id'));

        if (Input::has('type') && (Input::get('type') == 'consumer' || Input::get('type') == 1)) {
             $applications = \App\ConsumerApplication::with('category', 'advisor')->where('mobile_number', $user->mobile_number)->whereNull('is_deleted');
        }else{
            $applications = \App\ConsumerApplication::with('category', 'logs')->where('merchant_id', $user->merchant_id)->whereNull('is_deleted');
        }

        if(!empty($status)){
            $applications = $applications->whereIn('state',is_array($status) ? $status : [$status]);
        }
        $applicationsTotal = $applications->get();
        $applications = $applications->orderBy('updated_at', 'desc')->paginate(10);

        foreach ($applications as $key => &$application) {

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

            $application->purpose = isset($application->category->name) ? $application->category->name : '';
            if($application->state == "disbursement checklist done"){
                $application->state = "ready for disbursement";
            }
            if($application->state == "waiting for decision"){
                $application->state = "in-process";
            }
            if(in_array($application->state,['form completed', 'incomplete form'])) {
                $application->state = "new";
            }
            $application->status_created_at = $this->getStatusCreatedAt($application);
        }

        $data['consumer_applications'] = $applications;
        $data['status'] = $_status;
        $data['total_applications'] = ($applicationsTotal) ? count($applicationsTotal) : 0;
        $view = view('front.application.history_view', $data);

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

    public function getMerchantLogo(){
        $merchant = Merchant::find(\Auth::user()->merchant_id);
        if(isset($merchant->merchant_logo)){
            return $merchant->merchant_logo;
        }
        return '';
    }

    public function getStatusCreatedAt($application)
    {
        if ($application->logs){
            foreach ($application->logs as $log) {
                if(strtolower($log->status) == strtolower($application->state)){
                    return $log->created_at;
                }
            }
        }
        return $application->created_at;
    }

    public function getAcutalStatus($status, $application){
        foreach($application->statusarray as $key=>$_status){
            if(in_array($status, $_status)){
                return $key;
            }
        }
        return $status;
    }

    public function getApplicationLogout()
    {
        if (\Auth::check()) {
            \Auth::logout();
            return redirect()->to('application/login');
        } else {
            return redirect()->to('application/login');
        }
    }

    public function getOldPrivacyPolicy()
    {
        $data = array();
        $data['is_home'] = true;
        return view('front.privacy-policy', $data);
    }

    public function getCibilReport()
    {
        $data = array();
        $data['is_home'] = true;
        try {
            $file_path = 'C:\xampp\htdocs\creditfair\storage\1200_response.json';
            //$file_path = "/var/www/html/equifax/".$application_id."_response.json";
            $myfile = fopen($file_path, "r") or die("Unable to open file!");
            $file = fread($myfile,filesize($file_path));
            $report_data =  json_decode($file, true);
        }catch (\Exception $e) {
            return $e->getTrace();
        }

        $data['report_data'] = $report_data['soapenv:Envelope']['soapenv:Body']['sch:InquiryResponse'];
        return view('front.cibil-report', $data);

    }
    public function getFraudReport(Request $request, $file_path){
        try {
            $document = new ConsumerDocument(new Request(['consumer_application_file_id' => $request->get('consumer_application_file_id')]));
            $document->is_location_type = $request->get('isMerchantPipe') ? $request->get('isMerchantPipe') : '';
            $pdf = App::make('snappy.pdf.wrapper');
            $report = $pdf->loadView('front.fraud-report', ['report_data' => $file_path])->setOption('encoding', 'UTF-8')->setPaper('a4')->setOrientation('portrait');
            $document->uploadToS3('fraud_report_'.$request->get('bank_name'), $request->get('id'), $report->output());
        }catch (\Exception $e) {
            (new Slack(new Request(['title'=>'Finbit Error','fields'=>['error'=>$e->getMessage(),'line'=>$e->getLine(),'trace'=>$e->getTraceAsString(),'application_id'=>$request->get('id')]])))->send();
        }

        //$data['report_data'] = $report_data;
//        return $data['report_data'] = $report_data;
        //return view('front.fraud-report', $data);
    }


    public function getOldTermsConditions()
    {
        $data = array();
        $data['is_home'] = true;
        return view('front.terms-conditions', $data);
    }

    public function mandateActivationLinkRedirect($hash){
        $mandate = Mandate::where('mandate_id','LIKE','%'.$hash.'%')->first(['mandate_id']);
        if(isset($mandate->mandate_id)) {
            return redirect()->away($mandate->mandate_id);
        }
        return redirect()->to('/');
    }

    /* This function is to redirct the no credit fair link because DLT only support the whitelisted URL
        eg. https://creditfair.in/redirect/{URL}
    */
    public function redirectToLink(Request $request){
        return \redirect()->to(base64_decode($request->get('link')));
    }

    public function old_becomePartner(){
        //$hex = unpack("H*", file_get_contents('/home/sunil/Desktop/test.pdf'));
        //return $hex = current($hex);
        //$chars = pack("H*", $hex);
        $data['isapp'] = isset($_GET['is_app']) ? $_GET['is_app'] : 0;
        $data['is_home'] = true;
        return view('front.partner',$data);
    }

    public function getDocumentForWhatsApp($fileName){
        try {
            if (Storage::disk('storage')->exists($fileName)) {
                return response()->download(
                    storage_path('files/' . $fileName),
                    $fileName,
                    ['Content-Type' => 'application/pdf']
                );
            }
        }catch (\Exception $e){
            return \redirect('/');
        }

        return \redirect('/');
    }

    public function googleReview(){
        $mobile = false;
        $aMobileUA = array(
            '/iphone/i' => 'iPhone',
            '/ipod/i' => 'iPod',
            '/ipad/i' => 'iPad',
            '/android/i' => 'Android',
            '/blackberry/i' => 'BlackBerry',
            '/webos/i' => 'Mobile'
        );

        //Return true if Mobile User Agent is detected
        foreach($aMobileUA as $sMobileKey => $sMobileOS){
            if(isset($_SERVER['HTTP_USER_AGENT'])) {
                if (preg_match($sMobileKey, $_SERVER['HTTP_USER_AGENT'])) {
                    $mobile = true;
                }
            }
        }
        if ($mobile===true){
            return redirect()->to('https://www.google.com/search?source=hp&ei=yT7JXKi-N8H69QOv7rCgBQ&q=credit+fair&btnK=Google+Search&oq=credit+fair+&gs_l=psy-ab.3..0l7j0i22i30l3.970.3932..4149...2.0..0.305.2391.1j14j0j2......0....1..gws-wiz.....0..0i131j0i10.NNj9iLBPFVU&no_sw_cr=1&ved=1t%3A46160#btnK=Google%20Search&lkt=LocalPoiReviews&trex=m_t:lcl_akp,rc_f:nav,rc_ludocids:14144132659733704584,rc_q:Credit%2520Fair,ru_q:Credit%2520Fair');
        } else {
            return redirect()->to('https://www.google.com/search?source=hp&ei=yT7JXKi-N8H69QOv7rCgBQ&q=credit+fair+&btnK=Google+Search&oq=credit+fair+&gs_l=psy-ab.3..0l7j0i22i30l3.970.3932..4149...2.0..0.305.2391.1j14j0j2......0....1..gws-wiz.....0..0i131j0i10.NNj9iLBPFVU#btnK=Google%20Search&lrd=0x3be7d1ce4995a7e9:0xc44a0db7176daf88,3,,,');
        }
    }

    public function checkNetLoanAmount($offer, $loan_amount){
        $net_loan_amount = 0;
        switch ($offer->advance_type) {
            case 'emi':
                $net_loan_amount = ($loan_amount * ($offer->tenure - $offer->advance_emi))/$offer->tenure;
                break;
            case 'fixed_amount':
                $net_loan_amount = $loan_amount - $offer->advance_emi;
                break;
            case 'percentage':
                $net_loan_amount = ($loan_amount * (100 - $offer->advance_emi)) / 100;
                break;
        }
        return (int)round($net_loan_amount,0);
    }

    public function checkKycCondition($loanAmount, $kycRules)
    {
        foreach ($kycRules as $kycRule) {
            if ($kycRule->kyc_type == '1' || $kycRule->kyc_type == '2') {
                $conditionMet = $this->evaluateCondition($loanAmount, $kycRule->condition, $kycRule->net_loan_amount);
                if ($conditionMet) {
                    return $kycRule->kyc_type;
                }
            }
        }

        return 'No KYC requirement met';
    }

    private function evaluateCondition($loanAmount, $condition, $netLoanAmount)
    {
        switch ($condition) {
            case 'loan_amount_less_than':
                return $loanAmount <= $netLoanAmount;
            case 'loan_amount_more_than':
                return $loanAmount > $netLoanAmount;
            default:
                return false;
        }
    }

    public function generateTokens(Request $request){
        $application_id =  $request->get('application_id');
        $applicant_type =  $request->get('user');

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

        $applicationElement = ConsumerApplicationElement::where('application_id', $application_id)->orderBy('created_at', 'desc')->first(['onfido_skip','agreement_resign', 'co_app_onfido_skip']);
        $user_details = ConsumerApplication::where('id', $application_id)->first(['name', 'mobile_number', 'email', 'approved_amount', 'merchant_id', 'loan_amount', 'co_applicant_name', 'co_applicant_mobile_number', 'co_applicant_email']);

        if($applicant_type === 'Applicant') {
            $photo_kyc = ConsumerApplicationFiles::where('consumer_application_id', $application_id)->where(function ($query) {
                $query->where('file_type', 'self_attested_aadhar')->orwhere('file_type', 'self_attested_pan');
            })->first();
        }else{
            $photo_kyc = ConsumerApplicationFiles::where('consumer_application_id', $application_id)->where(function ($query) {
                $query->where('file_type', 'co_app_self_attested_aadhar')->orwhere('file_type', 'co_app_self_attested_pan');
            })->first();
        }

        $ekc_integration = new ekycIntegration();

        $user_type = $applicant_type === 'Applicant' ? 1 : 2;
        $kyc_details = KYCDetails::where('application_id', $application_id)->where('applicant_type', $user_type)->whereNull('deleted_at')->orderBy('id', 'desc')->first();

        if (!empty($kyc_details) && $applicationElement->agreement_resign == 0) {
            if (empty($kyc_details->response)) {
                $status = $ekc_integration->requestStatus($kyc_details->request_id, $application_id);
                if (isset($status['doc_type']) && count($status['doc_type']) > 0) {
                    $info = [];
                    foreach ($status['doc_type'] as $document) {
                        $info = $ekc_integration->getParsedInfo($kyc_details->request_id, $application_id, $document, true);
                    }

                    if(!empty($info) && $info != []){
                        (new Slack(new Request(['title' => 'Before Digio report gen 2', 'fields' => ['response' => $info, 'application_id' => $application_id]])))->send();
                        $ekc_integration->generateReport($kyc_details->request_id, $application_id, $info);
                    }
                    $data['status'] = 'OK';
                    $data['message'] = 'Redirect esign';
                    $data['link'] = 'esign/'.$hashed_id;
                    return response()->json($data, 200);
                }
            } else {
                $type = $kyc_details->applicant_type == 1 ? 'applicant' : 'coapplicant';
                $check_report = ConsumerApplicationFiles::where('consumer_application_id', $application_id)->where('file_type', 'like', '%digio report '.$type.'%')->first();
                if(empty($check_report)){
                    $ekc_integration->generateReport($kyc_details->request_id, $application_id, false);
                }

                $data['status'] = 'OK';
                $data['message'] = 'Redirect esign';
                $data['link'] = 'esign/'.$hashed_id;
                return response()->json($data, 200);
            }
        }


        if($applicant_type === 'Applicant'){
            $identifier = !empty($user_details->mobile_number) ? $user_details->mobile_number : (!empty($user_details->email) ? $user_details->email : '');
        }else{
            $identifier = !empty($user_details->co_applicant_mobile_number) ? $user_details->co_applicant_mobile_number : (!empty($user_details->co_applicant_email) ? $user_details->co_applicant_email : '');
        }


        $request_id = $ekc_integration->requestKYC($identifier, $application_id, $applicant_type);

        if(!$request_id){
            $request_id = $ekc_integration->requestKYC($identifier, $application_id, $applicant_type);
        }

        if(($applicant_type === 'Applicant' && $applicationElement->onfido_skip == 1) || ($applicant_type === 'Co-Applicant' && $applicationElement->co_app_onfido_skip == 1)){
            $data['status'] = 'OK';
            $data['message'] = 'Redirect esign';
            $data['link'] = 'esign/'.$hashed_id;
            return response()->json($data, 200);
        }else if(isset($photo_kyc) && !empty($photo_kyc)){
            $data['status'] = 'OK';
            $data['message'] = 'Redirect esign';
            $data['link'] = 'esign/'.$hashed_id;
            return response()->json($data, 200);
        }else{
            $onfidoIntegration = OnfidoIntegration::where('application_id', $application_id)->first(['id', 'applicant_type']);
            if (isset($onfidoIntegration->id) && (($applicant_type === 'Applicant' && $onfidoIntegration->applicant_type == 1) || ($applicant_type === 'Co-Applicant' && $onfidoIntegration->applicant_type == 2))) {
                $data['status'] = 'OK';
                $data['message'] = 'Redirect esign';
                $data['link'] = 'esign/'.$hashed_id;
                return response()->json($data, 200);
            }else{
                $token = $this->onfidoToken($application_id, $applicant_type);
            }
        }
        $data['application_id'] = $application_id;
        $data['request_id'] = isset($request_id) ? $request_id : '';
        $data['token'] = isset($token['token']) ? $token['token'] : '';
        $data['applicant_token_id'] = isset($token['applicant_id']) ? $token['applicant_id'] : '';
        $data['identifier'] = isset($identifier) ? $identifier : '';
        $data['source'] = 'link';
        $data['text_content'] = isset($content) ? $content : '';
        $data['user_details'] = $user_details;
        return response()->json($data, 200);
    }

    public function getKYCInfo(Request $request){

        $application_id =  $request->get('application_id');
        $applicant_type =  $request->get('user') == 'Applicant' ? 1 : 2;
        $status = $request->get('status');

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

        if($status == 'skip'){
            $data['status'] = 'OK';
            $data['message'] = 'skipped';
            $data['link'] = 'esign/'.$hashed_id;
            return response()->json($data, 200);
        }else{
            $r_id = KYCDetails::where('application_id', $application_id)->where('applicant_type', $applicant_type)->orderBy('id', 'desc')->first(['request_id']);

            $ekycIntegration =  new ekycIntegration();
            $status = $ekycIntegration->requestStatus($r_id['request_id'], $application_id);

            if(!isset($status['doc_type']) || $status['doc_type'] == ''){
                $status = $ekycIntegration->requestStatus($r_id['request_id'], $application_id);
                (new Slack(new Request(['title' => 'Digio request error', 'fields' => ['response' => $status]])))->send();
            }


            if(!isset($status['doc_type']) || $status['doc_type'] == ''){
                (new Slack(new Request(['title' => 'Digio fetch Failed', 'fields' => ['application_id' => $application_id]])))->send();
                $data['status'] = 'FAIL';
                $data['message'] = 'failed';
                return response()->json($data);
            }else {
                $info = [];
                foreach($status['doc_type'] as $document){
                    $info = $ekycIntegration->getParsedInfo($r_id->request_id, $application_id, $document, true);
                }
                if(!empty($info) && $info != []){
                    (new Slack(new Request(['title' => 'Before Digio report gen 3', 'fields' => ['response' => $info, 'application_id' => $application_id]])))->send();
                    $ekycIntegration->generateReport($r_id->request_id, $application_id, $info);
                }

                ConsumerApplicationElement::where('application_id', $application_id)->update(['onfido_skip' => 0]);
                $data['status'] = 'OK';
                $data['message'] = 'success';
                $data['link'] = 'esign/'.$hashed_id;
                return response()->json($data, 200);
            }
        }
    }

    public function getFeesData($id, $reconcile=false, $post_approval=true){

        if(Input::get('app')) {
            $hashids = new Hashids('Creditfair by CS', 20);
            $application_ids = $hashids->decode(Input::get('app'));
        }

        if(strpos(Input::has('applicant'), '2_') !== false || (isset($application_ids) && isset($application_ids[0]) && $application_ids[0] == 2)){
            return [];
        }

        $applicationData = ConsumerApplication::with('proFormaInvoice','emi','merchant','bank_details','mandate','lender','activeOffer', 'foreclosed_transaction')->where('id', $id)->first();
        $applicationFiles = ConsumerApplicationFiles::where("consumer_application_id",$applicationData->id);
        $application = new ConsumerApplicationController();
        $hashids = new Hashids('Creditfair by CS', 20);
        $request = new Request();
        $consumerDocument = new ConsumerDocument($request);
        $disbursementController = new DisbursementController($request);

        $breakupLogs = [];
        if(isset($applicationData->foreclosed_transaction->id) && $applicationData->foreclosed_transaction->id){
            $breakupLogs = ForeclosureBreakup::where('application_id', $id)->orderBy('created_at', 'desc')->first();
        }

        $fees = [];
        if ($applicationData && $applicationData->emi && $applicationData->emi->processing_fee) {

            $process['proFormaInvoice'] = $applicationData->proFormaInvoice;
            $process['merchant_processing_collected'] = isset($applicationData->merchant->is_collected) && $applicationData->merchant->is_collected == 1 ? $applicationData->merchant->is_collected : (isset($applicationData->proFormaInvoice) && $applicationData->proFormaInvoice->processing_fee_by_merchant == 1 ? $applicationData->proFormaInvoice->processing_fee_by_merchant : 0);
            $process['processing_fee_first_emi'] = ((isset($applicationData->activeOffer->processing_fee_first_emi) && ($applicationData->merchant->is_collected == 0 && $applicationData->activeOffer->processing_fee_first_emi == 1)) ? $applicationData->activeOffer->processing_fee_first_emi : 0);
            $process['lender'] = $applicationData->lender;

            if ($consumerDocument->isProcessingFeeCollected($process)) {
                if (!$application->isProcessingFeeApplicable($id)) {
                    $processingFeeData = $process;
                    // $processingFeeData['lender'] = $applicationData->lender;
                    $processingFeeData['consumer_emi'] = $applicationData->emi;
                    $paid_processing_fee = 0;
                    $emiPayment = PaymentTransaction::where('application_id', $id)->where('payment_for','processing_fee')->whereNull('is_deleted_at')->get(['id', 'amount']);
                    if (count($emiPayment) > 0) {
                        foreach ($emiPayment as $idx=>$payment_txns) {
                            $paid_processing_fee += $payment_txns->amount;
                        }
                    }
                    $processingFeeData['pending_amount'] = $applicationData->emi->processing_fee - $paid_processing_fee;
                    if(count($emiPayment) == 0 || $processingFeeData['pending_amount'] > 0) {
                        if($breakupLogs == [] || $breakupLogs->pf_due < 1){
                            // $fees['processing_fee_link'] = $application->sendProcessingFeeLink($processingFeeData, $applicationData);
                            $fees['payment_details']['Processing Fee'] = ['amount' => $processingFeeData['pending_amount'], 'purpose' => 'processing_fee'];
                        }
                    }
                }
            }
        }

        if($insurance_fee_amount = $disbursementController->isCustomerPayingInsuranceFee($applicationData)){
            $emiPayment = PaymentTransaction::where('application_id', $id)->where('payment_for','insurance_fee')->whereNull('is_deleted_at')->get(['id', 'amount']);
            $paid_insurance_fee = 0;
            if (count($emiPayment) > 0) {
                foreach ($emiPayment as $idx=>$payment_txns) {
                    $paid_insurance_fee += $payment_txns->amount;
                }
            }
            $insurance_fee_amount = $insurance_fee_amount - $paid_insurance_fee;
            if(count($emiPayment) == 0 || $insurance_fee_amount > 0) {
                // $fees['insurance_fee_link'] = $application->sendInsuranceFeeLink($insurance_fee_amount, $applicationData);
                $fees['payment_details']['Insurance'] = ['amount' => $insurance_fee_amount, 'purpose' => 'insurance_fee'];
            }
        }

        if ($cf_advance_amount = $disbursementController->isCFCollectingAdvance($applicationData)) {
            $emiPayment = PaymentTransaction::where('application_id', $id)->where('payment_for','advance_amount')->whereNull('is_deleted_at')->get(['id', 'amount']);
            $paid_advance_fee = 0;
            if (count($emiPayment) > 0) {
                foreach ($emiPayment as $idx=>$payment_txns) {
                    $paid_advance_fee += $payment_txns->amount;
                }
            }
            $cf_advance_amount = $cf_advance_amount - $paid_advance_fee;
            if(count($emiPayment) == 0 || $cf_advance_amount > 0) {
                if($breakupLogs == [] || $breakupLogs->advance_due < 1) {
                    // $fees['advance_amount_link'] = $application->sendAdvanceAmountLink($cf_advance_amount, $applicationData);
                    $fees['payment_details']['Down Payment'] = ['amount' => $cf_advance_amount, 'purpose' => 'advance_amount'];
                }
            }
        }
        if($applicationData->lender_id == Singularity::$lender_id){
            $legal_charges_applicable_for_homeville =$consumerDocument->isProcessingFeeCollectedForHomeville($applicationData);
        }else{
            $legal_charges_applicable_for_homeville = false;
        }
        
        // Legal charges
        if (isset($fees['payment_details']['Processing Fee'])|| $legal_charges_applicable_for_homeville) {
            if ($legal_charges = $applicationData->emi->legal_charges) {
                $emiPayment = PaymentTransaction::where('application_id', $id)->where('payment_for','legal_charges')->whereNull('is_deleted_at')->get(['id', 'amount']);
                $paid_legal_charges = 0;
                if (count($emiPayment) > 0) {
                    foreach ($emiPayment as $idx=>$payment_txns) {
                        $paid_legal_charges += $payment_txns->amount;
                    }
                }
                $legal_amount = $legal_charges - $paid_legal_charges;
                if(count($emiPayment) == 0 || $legal_amount > 0) {
                    $fees['payment_details']['Legal Charges'] = ['amount' => $legal_amount, 'purpose' => 'legal_charges'];
                }
            }
        }

        if ($reconcile) {
            return $fees['payment_details'];
        }

        // total payment calculations
         $fees['payment_details']['Total Payment'] = ['amount' => ($fees['payment_details']['Down Payment']['amount'] ?? 0) +
                                                                ($fees['payment_details']['Processing Fee']['amount'] ?? 0) +
                                                                ($fees['payment_details']['Insurance']['amount'] ?? 0) +
                                                                ($fees['payment_details']['Legal Charges']['amount'] ?? 0),
                                                    'purpose' => 'total_fee'];

         if ($fees['payment_details']['Total Payment']['amount'] > 0) {
            $fees['total_payment_link'] = $application->sendTotalPaymentLink($fees['payment_details']['Total Payment']['amount'], $applicationData);
         }
        if (isset($fees['total_payment_link']) && $post_approval) {
            $appendString = env('APP_CONNECTION') == 0 ? "&post_approval=true" : "?post_approval=true";
            $fees['total_payment_link'] = $fees['total_payment_link'].$appendString;
        }

        $mandate = Mandate::where('consumer_application_id', $id)->whereIn('status',['active','submitted'])->first(['id']);
        $application_hashed_id = $hashids->encode($id);
        $fees['bank']['validation'] = false;
        if(!isset($mandate->id) && $applicationData->lender_id != Vivriti::$lender_id && $applicationData->lender_id != Singularity::$lender_id){
            $isFullAmount_hashed_id = $hashids->encode(2);
            $url = asset("enachrequest/id/" . $application_hashed_id."/".$isFullAmount_hashed_id);
            $fees['set_auto_debit'] = $url;
            if (isset($applicationData->bank_details->bank_name)) {
                $bank_validation = json_decode($applicationData->bank_details->karza_response);
                if($bank_validation && $applicationData->bank_details->karza_response && $applicationData->bank_details->karza_response != 'false' && isset($bank_validation->result) && isset($bank_validation->result->bankResponse) && ($bank_validation->result->bankResponse == 'Transaction Successful' || $bank_validation->result->bankResponse == 'SUCCESSFUL TRANSACTION')) {
                    $fees['bank']['validation'] = true;
                } else {
                    $fees['bank']['validation'] = false;
                    $fees['bank']['bank_name'] = $applicationData->bank_details->bank_name;
                    $fees['bank']['account_name'] = $applicationData->bank_details->name;
                    $fees['bank']['branch_name'] = $applicationData->bank_details->branch_name;
                    $fees['bank']['ifsc_code'] = $applicationData->bank_details->ifsc_code;
                    $fees['bank']['account_number'] = $applicationData->bank_details->account_number;
                    $fees['bank']['account_type'] = $applicationData->bank_details->account_type;
                }
            }
        }

        // Co-applicant bank details checked, commented for now
        $fees['co_applicant_bank'] = true;
        // if ($applicationData->co_applicant_name != '' || !empty($applicationData->co_applicant_name)) {
        //     $fees['co_applicant_bank'] = false;
        //     $fees['co_applicant_bank_url'] = asset("enachrequest/id/".$application_hashed_id."?type=2");
        //     $coAppBank = Bank::where(['application_id' => $id, 'applicant_type' => 2])->first(['id', 'karza_response']);
        //     if (isset($coAppBank->id)) {
        //         $validation = json_decode($coAppBank->karza_response);
        //         if ($validation->result->bankResponse == 'SUCCESSFUL TRANSACTION') {
        //             $fees['co_applicant_bank'] = true;
        //         }
        //     }
        // }


        // Sanction letter
        if (in_array($applicationData->state, ['approved', 'disbursement checklist done', 'disbursement query', ]) &&
        $applicationFiles->where('file_type', 'sanction_letter')) {
            $fees['sanction_letter'] = Shortio::getUrl(asset('documents/' . $hashids->encode($id) . '/' . base64_encode(str_replace(' ', '_', strtolower('sanction_letter')))));
        }

        return $fees;
    }

    public function checkKYCStatus($applicationId) {
        $application = DB::select("select co_applicant_name from consumer_application where id = " . $applicationId);
        $applicant = [
            'kyc_completed' => false,
            'kyc_status' => null
        ];
        if (!empty($application[0]->co_applicant_name)) {
            $co_applicant = [
                'kyc_completed' => false,
                'kyc_status' => null
            ];
        }
        $karzaKYCRecords = KarzaVideoAttribute::where('application_id', $applicationId)
            ->whereIn('applicant_type', [1, 2])
            ->orderBy('id', 'desc')
            ->get(['id']);
        $digioKYCDetails = DigioVKYC::where('application_id', $applicationId)->get(['id', 'kyc_journey', 'kyc_status', 'applicant_type']);
        if (count($karzaKYCRecords) > 0) {
            foreach ($karzaKYCRecords as $karzaRecord) {
                $customer_webhook = KarzaVideoWebhook::where('karza_id', $karzaRecord->id)->get(['data', 'applicant_type']);
                if(!empty($customer_webhook)){
                    foreach ($customer_webhook as $key => $value) {
                        $kyc_data = json_decode($value->data);
                        if (isset($kyc_data->approvedByAgent) && $kyc_data->approvedByAgent == "ACCEPTED") {
                            // $applicantType = substr($kyc_data->customerId, -1);
                            if ($value->applicant_type == 1) {
                                $applicant['kyc_completed'] = true;
                            } else {
                                $co_applicant['kyc_completed'] = true;
                            }
                        }
                        if (isset($kyc_data->approvedByAuditor) && $kyc_data->approvedByAuditor == "ACCEPTED") {
                            // $applicantType = substr($kyc_data->customerId, -1);
                            if ($value->applicant_type == 1) {
                                $applicant['kyc_status'] = 'approved';
                            } else {
                                $co_applicant['kyc_status'] = 'approved';
                            }
                        }
                        if (isset($kyc_data->approvedByAuditor) && $kyc_data->approvedByAuditor == "REJECTED") {
                            // $applicantType = substr($kyc_data->customerId, -1);
                            if ($value->applicant_type == 1) {
                                $applicant['kyc_status'] = 'rejected';
                            } else {
                                $co_applicant['kyc_status'] = 'rejected';
                            }
                        }
                    }
                }
            }
        }
        if (count($digioKYCDetails) > 0) {
            foreach ($digioKYCDetails as $digioData) {
                if ($digioData->kyc_journey == 'complete') {
                    if ($digioData->applicant_type == 1) {
                        $applicant['kyc_completed'] = true;
                        $applicant['kyc_status'] = $digioData->kyc_status; // confirm if null is to be considered as rejected
                    } else {
                        $co_applicant['kyc_completed'] = true;
                        $co_applicant['kyc_status'] = $digioData->kyc_status;
                    }
                }
            }
        }
        if (isset($co_applicant)) {
            return \response()->json([
                'status' => 'OK',
                'applicant' => $applicant,
                'co_applicant' => $co_applicant
            ], 200);
        }
        return \response()->json([
            'status' => 'OK',
            'applicant' => $applicant
        ], 200);
    }

    public function merchantesign($id){
        $hashids         = new Hashids('Creditfair by CS', 20);
        $application_ids = $hashids->decode($id);
        $application_id = $application_ids[0];
        $type = "Merchant Agreement Esign";
        $signed_data = DigitalSignDetails::where('application_id',$application_id)->where('type','merchant')->orderBy('applicant', 'asc')->get();
        if(isset($signed_data[0]['isagreementsigned']) && $signed_data[0]['isagreementsigned'] == 1) {
            $data = array("application_ids" => $application_id);
            return view('front.esign-congrats-merchant', $data);
        }
        $data = Merchant::with('offer','module')->where('id', $application_id)->first();
        $lender = Lenders::where('id', 2)->first();
        $opendatetime = date('Y-m-d H:i:s');
        return view('front.merchantdigitalpdf',['http' => 'https', 'merchant'=>$data,'lender'=>$lender,'opendatetime'=>$opendatetime,'pdf' => 0]);

       }

    public function merchantdigitalsignupdate($hashed_id){
        $hashids         = new Hashids('Creditfair by CS', 20);
        $application_ids = $hashids->decode($hashed_id);
        $id = $application_ids[0];
        $aggrementgenerate = 0;
        $data = array("application_ids" => $id);
        $application = ConsumerApplication::where('id', $id)->first(['id','lender_id']);
        $lender_id = isset($application->lender_id) ? $application->lender_id : 2;
        $merchant = Merchant::with('offer','module')->where('id', $id)->first();
        $lender = Lenders::where('id', $lender_id)->first();

        $signed_data = DigitalSignDetails::where('application_id',$id)->where('type','merchant')->orderBy('applicant', 'asc')->get();
            if(isset($signed_data[0]['applicant'])){
               $aggrementgenerate = $signed_data[0]['isagreementsigned'];
                $signed_data[0]['consent'] = "I have been read out and explained, the contents of the master agreement to partner with K. M. Global Credit Pvt. Ltd. and I have signed the said documents after having understood them and by signing the same I do hereby agree to abide by all the general terms and conditions of the master agreement.";
            }
            if($aggrementgenerate == 1){
                //return view('front.esign-congrats-merchant', $data);
            }
            $type = "Merchant Agreement Esign";
            $pdf = App::make('snappy.pdf.wrapper');
            if($merchant->category_id ==6){
                $pdf->loadView('admin.documents.merchant_agreement_solar', ['merchant' => $merchant, 'pdf' => 1, 'signed_data' => $signed_data, 'lender' => $lender])->setOption('encoding', 'UTF-8')->setPaper('a4')->setOrientation('portrait');
            }else{
                $pdf->loadView('admin.documents.merchant_agreement_v1', ['merchant' => $merchant, 'pdf' => 1, 'signed_data' => $signed_data, 'lender' => $lender])->setOption('encoding', 'UTF-8')->setPaper('a4')->setOrientation('portrait');
            }
            // $pdf->setOption('header-html', view('admin.editor.header', ['lender' => $lender])->render());
            $header = '<HTML
                <!DOCTYPE html>
                <html>
                <head>
                <style type="text/css">
                    body { margin: 0;}
                </style>
                </head>
                <body style="float:right">
                <img src="' . $lender->logo . '" style="width: 57px;float: right;">
                </body>
                </html>';
            $pdf->setOption('header-html',$header);
            $pdf->setOption('margin-top', 20);
            $pdf->setOption("footer-right", "Page [page] from [topage]");
            $pdf->setOption('footer-font-size', 10);
            $pdf->setOption('margin-bottom', 30);

            $pdf->setOption('footer-html', view('admin.editor.footer', ['type' => "Merchant Agreement", 'lender' => $lender])->render());
            //  return $pdf->download($merchant->merchant_name.' mlg.pdf');

            $file_path = $this->uploadToS3(str_replace(' ','_',strtolower($type)), $id, $pdf->output(),1);

            try {
                $audit_trail = new ConsumerApplicationController();
                if ($audit_trailData = $audit_trail->auditTrail($id, 'merchant')) {
                    $this->uploadToS3('merchant_audit_trail', $id, $audit_trailData, 1);
                }
            }catch (\Exception $E){

            }

            $field =array();
            array_push($field,array('title'=>"Merchant Name","value"=> $merchant->merchant_name,"short" => true));
            array_push($field,array('title'=>"Merchant Mobile","value"=> $merchant->contact_number,"short" => true));
            array_push($field,array('title'=>"Merchant Email","value"=> $merchant->email,"short" => true));
            array_push($field,array('title'=>"Status","value"=> "Signed","short" => true));
            $title = 'New Agreement Signed';
            $url = "https://hooks.slack.com/services/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";

            $payload = json_encode(array('text'=>$title, "username" => "Merchant",'attachments'=>array(array('fields'=>$field))));
            $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => $url,
                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=".$payload,
                CURLOPT_HTTPHEADER => array(
                    "Content-Type: application/x-www-form-urlencoded",
                ),
            ));

            $response = curl_exec($curl);


        if(isset($signed_data[0]['id'])) {
                $update_signed_data = DigitalSignDetails::find($signed_data[0]['id']);
                $update_signed_data->isagreementsigned = 1;
                $update_signed_data->save();

                MerchantModule::where('merchant_id',$id)->where('status',3)->update(['status' => 1]);
            }
            if(isset($signed_data[1]['id'])) {
                $update_signed_data = DigitalSignDetails::find($signed_data[1]['id']);
                $update_signed_data->isagreementsigned = 1;
                $update_signed_data->save();
            }
        return view('front.esign-congrats-merchant', $data);
    }

    public function sendslackmessage(){

    }

    public function digitalsignupdate($hashed_id, $system = false){
        Dump::log(['message' => 'digitalsignupdate started', 'hash_id' => $hashed_id], Dump::$ESIGN);
        $hashids         = new Hashids('Creditfair by CS', 20);
        $application_ids = $hashids->decode($hashed_id);
        $id = $application_ids[0];
        $aggrementgenerate = 0;
        $data = array("application_ids" => $id);
        $applicant_count = 0;
        $consumer_details = ConsumerApplication::where('id',$id)->first(['name','co_applicant_name']);
        $applicant_name =$consumer_details['name'];
        $co_applicant_name = $consumer_details['co_applicant_name'];
        if($applicant_name != ""){
            $applicant_count = $applicant_count + 1;
        }
        if($co_applicant_name != ""){
            $applicant_count = $applicant_count + 1;
        }
        $signed_data = DigitalSignDetails::where('application_id',$id)->where('type','consumer')->orderBy('applicant', 'asc')->get();
        Dump::log(['message' => 'digitalsignupdate', 'id' => $id, 'signed count' => count($signed_data), 'applicant_count' => $applicant_count], Dump::$ESIGN);
        if(count($signed_data) == $applicant_count){
            Dump::log(['message' => 'digitalsignupdate count checked', 'id' => $id], Dump::$ESIGN);
            if($aggrementgenerate == 1){
                Dump::log(['message' => 'digitalsignupdate getFeesData returned', 'id' => $id], Dump::$ESIGN);
                $data['fees'] = $this->getFeesData($id);
                return view('front.esign-congrats', $data);
            }

            Dump::log(['message' => 'digitalsignupdate calling sendEsignUpdate', 'id' => $id], Dump::$ESIGN);
            $this->sendEsignUpdate($id, $system);
        }
        Dump::log(['message' => 'digitalsignupdate calling getFeesData', 'id' => $id], Dump::$ESIGN);
        $data['fees'] = $this->getFeesData($id);
        $data['kycDetails'] = (new PostApprovalController())->checkKYCStatus($id)->getData();
        $data['applicantType'] = $hashids->decode(Input::get('app'))[0] ?? 1;
        $bnpl = ConsumerApplicationElement::where('application_id',$id)->first(['is_bnpl']);
        $data['is_bnpl'] = $bnpl->is_bnpl;
        Dump::log(['message' => 'digitalsignupdate rendering congrats screen', 'id' => $id], Dump::$ESIGN);
        return view('front.esign-congrats', $data);
    }

    public function sendEsignUpdate($id, $system){

        //Do not generate if we are doing loan hypothecation
//        if ((new ApiController())->canHypothecated($id)){
//            return response()->json(['status' => 'FAIL'], 400);
//        }

        Dump::log(['message' => 'sendEsignUpdate creating esign_customer_update'], Dump::$ESIGN);
        $jobs = JobProvider::where('from', 'esign_customer_update')->where('application_id',$id)->where('is_available',0)->first(['id']);
        if(!isset($jobs->id)) {
            $payload[] = [
                'payload' => json_encode(['id' => $id, 'system' => $system]),
                'from' => 'esign_customer_update',
                'application_id' => $id,
                'available_at' => Carbon::now()->toDateTimeString(),
                'created_at' => Carbon::now()->toDateTimeString()
            ];

            $job = new Jobs();
            Dump::log(['message' => 'sendEsignUpdate adding insertQueue', 'payload' => $payload], Dump::$ESIGN);
            $job->insertQueue($payload);
        }
    }



    public function sendEsignToCustomer($id, $system = ''){
        $aggrementgenerate = 0;
        $data = array("application_ids" => $id);
        $applicant_count = 0;
        $consumer_details = ConsumerApplication::where('id',$id)->first();
        $applicant_name =$consumer_details['name'];
        $co_applicant_name = $consumer_details['co_applicant_name'];
        if($applicant_name != ""){
            $applicant_count = $applicant_count + 1;
        }
        if($co_applicant_name != ""){
            $applicant_count = $applicant_count + 1;
        }

        $ln = Lenders::where('id', $consumer_details['lender_id'])->select('name')->first();
        if(!empty($ln->name)) {
            $ln = $ln->name;
        }

        // if avanse is the lender on the application
        if ($consumer_details['lender_id'] === ConsumerApplication::AVANSE_LENDER_ID ) { //&& $consumer_details['approved_amount'] > 300000
            $lavObj = LoanAgreementVendor::checkIfEntryExist($id);
            if ($lavObj !== false) {
                if(true === $lavObj->checkIfSignDone()) {
                    $type = "Loan Agreement Esign";
                    $request = new Request();
                    $request->attributes->add(['type'=>$type]);
                    $consumerDocument = new ConsumerDocument($request);
                    $viewParameter = ($consumerDocument->getDocument($id));
                    $fileOutput = $this->downloadDocument($id,$viewParameter, '', $system);
                    if(!empty($consumer_details->email)) {
                        $this->sendCustomerEsignEmail(['name' => $consumer_details->name, 'phone'=>$viewParameter['user']['customer_mobile'], 'email' => $consumer_details->email,'id'=>$id, 'fileOutput' => $fileOutput, 'ln' => $ln], $viewParameter);
                    }
                    if(!empty($consumer_details->co_applicant_email)) {
                        $this->sendCustomerEsignEmail(['name' => $consumer_details->co_applicant_name, 'phone'=> $viewParameter['user']['co_applicant_mobile'], 'email' => $consumer_details->co_applicant_email,'id'=>$id, 'fileOutput' => $fileOutput, 'ln' => $ln], $viewParameter);
                    }
                    unset($consumer_details, $viewParameter, $consumerDocument);
                    //return true;
                } else {
                    //return false;
                }
            } else {
                //return false;
            }
        } else {

            $signed_data = DigitalSignDetails::where('application_id',$id)->where('type','consumer')->orderBy('applicant', 'asc')->get();
            $geolocation = UserGeolocation::where('_id', $id)->where('id_type', 'application_id')->orderBy('applicant_type', 'asc')->get();
            if(count($signed_data) == $applicant_count){


                $sanctionLogs = SanctionAmountLogs::where('application_id', $id)->orderBy('created_at', 'desc')->first(['id']);
                if (isset($sanctionLogs->id)){
                    SanctionAmountLogs::where('id', $sanctionLogs->id)->update(['is_esing_done' => 1]);
                }

                if(isset($signed_data[0]['applicant'])){
                    if(isset($signed_data[0]['isagreementsigned']) && $signed_data[0]['isagreementsigned'] == 1) {
                        $aggrementgenerate = 1;
                    }
                    $signed_data[0]['consent'] = $this->vernaculardeclarationarray[$signed_data[0]['language']];
                    $signed_data[0]['longitude'] = $geolocation[0]['longitude'] ?? '';
                    $signed_data[0]['latitude'] = $geolocation[0]['latitude'] ?? '';
                }
                if(isset($signed_data[1]['applicant'])){
                    if(isset($signed_data[1]['isagreementsigned']) && $signed_data[1]['isagreementsigned'] == 1) {
                        $aggrementgenerate = 1;
                    }
                    $signed_data[1]['consent'] = $this->vernaculardeclarationarray[$signed_data[1]['language']];
                    $signed_data[1]['longitude'] = $geolocation[1]['longitude'] ?? '';
                    $signed_data[1]['latitude'] = $geolocation[1]['latitude'] ?? '';
                }

                if($aggrementgenerate == 1 && !$system){
                    $data['fees'] = $this->getFeesData($id);
                    return view('front.esign-congrats', $data);
                }

                $type = "Loan Agreement Esign";
                $request = new Request();
                $request->attributes->add(['type' => $type]);
                $consumerDocument = new ConsumerDocument($request);
                $viewParameter = ($consumerDocument->getDocument($id));

                $fileOutput = $this->downloadDocument($id, $viewParameter, $signed_data, $system);

                try {
                    $audit_trail = new ConsumerApplicationController();
                    if ($audit_trailData = $audit_trail->auditTrail($id, 'consumer')) {
                        $this->uploadToS3('consumer_audit_trail', $id, $audit_trailData);
                    }
                } catch (\Exception $e) {

                }

                if(isset($signed_data[0]['id'])) {
                    $update_signed_data = DigitalSignDetails::find($signed_data[0]['id']);
                    $update_signed_data->isagreementsigned = 1;
                    $update_signed_data->save();
                    $this->sendCustomerEsignEmail(['name' => $applicant_name, 'phone'=>$viewParameter['user']['customer_mobile'], 'email' => $consumer_details->email,'id'=>$id, 'fileOutput' => $fileOutput, 'ln' => $ln], $viewParameter);
                }
                if(isset($signed_data[1]['id'])) {
                    $update_signed_data = DigitalSignDetails::find($signed_data[1]['id']);
                    $update_signed_data->isagreementsigned = 1;
                    $update_signed_data->save();
                    $this->sendCustomerEsignEmail(['name' => $co_applicant_name, 'phone'=> $viewParameter['user']['co_applicant_mobile'], 'email' => $consumer_details->co_applicant_email,'id'=>$id, 'fileOutput' => $fileOutput, 'ln' => $ln], $viewParameter);
                }
            }
        }
    }

    public function sendCustomerEsignEmail($application, $data){
        try {
            $isCarepay = isset($data['user']['merchant_id']) && $data['user']['merchant_id'] == 7865 ? 1 : 0;
            $isCarepayAnchor = isset($data['application']->merchant->anchor_merchant_id) && isset($data['application']->merchant->anchor_merchant_id) == 7865 ? 1 :0;
            $consumer_app_link = 'https://lnk.creditfair.in/Wgmx';//\Bitly::getUrl('https://play.google.com/store/apps/details?id=com.consumer.creditfair&hl=en_US');
            if(\request()->has('action_type')){
                $subject = "Revised Loan Agreement";
//                $message = "Dear ".$application['name'].",<br/>Please go through your Revised Loan Agreement. Feel free to contact us on +919967235047 for any issues.<br/>Regards,<br/>Team Credit Fair";
                $message = "Dear ".$application['name'].",<br/>Please go through your Revised Loan Agreement";
                $entity = ['templateid' => '1307159973922629947', 'entityid' => Templates::$entityid];
            }else if($isCarepay == 1 || $isCarepayAnchor == 1){
                $subject = 'Thanks for signing the loan agreement';
                // $message = "Dear " . $application['name'] . ",<br/><br/> Thanks for signing the loan agreement for your purchase from " . $data['user']['merchant_name'] . " of Rs " . $data['user']['loan_amount'] . " and loan ID " . $data['user']['proFormaInvoice']->loan_application_no . ". Please complete pending requirements to arrange the disbursement";
                $message = "Dear " . $application['name'] . "<br/>  Thanks for signing the loan agreement for your purchase from " . $data['user']['merchant_name'] . ". <br/>Credit Fair K. M. Global Credit Private Limited";
                $entity = ['templateid' => '1307169726850269090', 'entityid' => Templates::$entityid];
            } else {
                $subject = 'Thanks for signing the loan agreement';
                $message = "Dear ".$application['name']." , Thanks for signing the loan agreement for your purchase from ".$data['user']['merchant_name']." Please download our app to check what are the pending requirements ".$consumer_app_link." Regards, Credit Fair (KM Global)";
                $entity = ['templateid' => '1307173458872562454', 'entityid' => Templates::$entityid];
            }

            $isMasai = isset($data['user']['merchant_id']) && $data['user']['merchant_id'] == 6543 ? 1 : 0;

            if (!empty($application['phone']) && !$isMasai) {
                $templateId = Templates::$sign_agreement_c1;

                $args = [$application['name'], $data['user']['merchant_name']];
                if(\request()->has('action_type')){
                    send_sms($application['phone'], ['message'=>$message,'id'=>$application['id'],'id_type'=>'application_id','templateId' => Templates::$revised_loan_agreement_c2, 'args' => [$application['name']], 'templateDetails' => $entity]);
                }elseif($isCarepay == 1 || $isCarepayAnchor == 1){
                    send_sms($application['phone'], ['message'=>$message,'id'=>$application['id'],'id_type'=>'application_id','templateId' => Templates::$agrement_signing_thanks_v1, 'args' => $args, 'templateDetails' => $entity]);
                }else{
                    send_sms($application['phone'], ['message'=>$message,'id'=>$application['id'],'id_type'=>'application_id', 'templateId' => $templateId, 'args' => $args, 'templateDetails' => $entity]);
                }
            }

            $application_element = ConsumerApplicationElement::where('application_id', $application['id'])->first(['is_bnpl']);

            $filename = 'Loan Agreement Esign.pdf';
            if($application_element->is_bnpl){
                $filename = 'Esign Service Agreement.pdf';
            }

            if (!empty($application['email']) && !$isMasai && isset($data['user']['merchant_id']) && $data['user']['merchant_id']!= _env("Finsall_id")) {
                \Mail::send('emails.reminders.basic_reminder',
                    [
                        'body' => $message,
                        'lender_id' => !empty($data['lender']['id']) ? $data['lender']['id'] : ''
                    ]
                    , function ($message) use ($application, $subject, $filename) {
                        $message->to($application['email'])->subject($subject);
                        // $message->cc('centralops@creditfair.in');
                        if(isset($application['fileOutput']) && $application['fileOutput']){
                            $message->attachData($application['fileOutput'], $filename);
                        }
                    });
            }
        }catch (\Exception $e){
            return 'Exception occurred while sending customer esign email';
        }
    }

//    public function esign($id){
//        $hashid = explode("_",$id);
//        $hashids         = new Hashids('Creditfair by CS', 20);
//        $application_ids = $hashids->decode($hashid[1]);
//        $application_id = $application_ids[0];
//
//        $type = "Loan Agreement Esign";
//        $request = new Request();
//        $request->attributes->add(['type'=>$type]);
//        $consumerDocument = new ConsumerDocument($request);
//        $viewParameter = ($consumerDocument->getDocument($application_id));
//        $file_url = $this->downloadDocument($application_id,$viewParameter);
//
//        $url = _env('MACHURL')."api/esign";
//        $secureKey = _env('MANCHSECUREKEY');
//        $organizationKey = _env('MANCHORGANIZATIONKEY');
//        if($hashid[0] == 1) {
//            $applicanttemplateKey = _env('MANCHAPPLICANTTEMPLATEKEY');
//            $firstName = $viewParameter['user']['customer_name'];
//
//        }else {
//            $applicanttemplateKey = _env('MANCHCOAPPLICANTTEMPLATEKEY');
//            if(isset($viewParameter['user']['co_applicant_name'])) {
//                $firstName = $viewParameter['user']['co_applicant_name'];
//            }else{
//                $firstName = "";
//            }
//        }
//        $transactionType = "TYPE3";
//        $documentType = "Agreement";
//        $transactionId = "NN_".time();
//        $lastName = "";
//        $callbackURL = asset("esignupdate/id/".$id);
//        $expiryDays = 14;
//        $documentTypeUrl = $file_url;
//        $opendatetime = date('Y-m-d H:i:s');
//        $document = array("documentType"=>$documentType,"documentTypeUrl"=> $documentTypeUrl);
//        $manch_data = (array("transactionType"=> $transactionType,"secureKey"=>$secureKey,"organizationKey"=>$organizationKey,"transactionId"=> $transactionId,"firstName"=> $firstName,"lastName"=> $lastName,"templateKey"=> $applicanttemplateKey,"callbackURL"=> $callbackURL,"expiryDays"=> $expiryDays,"documents"=>array($document)));
//        return view('front.digitalpdf',['fileurl'=>$file_url,'opendatetime'=>$opendatetime,'user'=>$viewParameter['user'],'id'=>$application_id,'hasdid'=>$id,'data'=>$viewParameter['data'],'pdf'=>0,'machdata'=>$manch_data,'manch_url'=>$url]);
//    }

    public function downloadDocument($id,$viewParameter,$signed_data= "", $system = 0){

        $type = "loan_agreement_esign";
        $loanAgreement = ConsumerApplicationFiles::where('consumer_application_id',$id)
                        ->where('file_type',$type)
                        ->orderBy('updated_at', 'desc')
                        ->first();
        if($loanAgreement) {
            if (Storage::disk('s3')->exists($loanAgreement->file_path)) {
                return Storage::disk('s3')->get($loanAgreement->file_path);
            }
            return "https://s3.ap-south-1.amazonaws.com/".(_env('AWS_BUCKET'))."/".$loanAgreement->file_path;
        }

        if($signed_data == ""){
            $signed_data = new DigitalSignDetails();
        }
        $type = "Loan Agreement Esign";
        $loanAgreement = ConsumerApplicationFiles::where('consumer_application_id',$id)->where('file_type',str_replace(' ','_',strtolower($type)))->orderBy('updated_at', 'desc')->first();

        if($loanAgreement) {
            $file_url = "https://s3.ap-south-1.amazonaws.com/creditfair-customer-documents/".$loanAgreement->file_path;
            return $file_url;
        }

        $isInsuranceTaken = 0;
        $save_agreement_document_details = [];
        $proforma = ProFormaInvoice::where('application_id',$id)->first();
        if ($proforma && isset($proforma->insurance_premium_applicable) && $proforma->insurance_premium_applicable == 1 && !empty($proforma->insurance_premium_amount) && $proforma->insurance_premium_amount != null && $proforma->insurance_premium_amount > 0) {
            $isInsuranceTaken = 1;
        }

        $pdf = App::make('snappy.pdf.wrapper');
        $consumer_application_elements = ConsumerApplicationElement::where('application_id',$id)->first();

        if(isset($viewParameter['lender']->id) && $viewParameter['lender']->id == Services::$lender_id){
            $save_agreement_document_details = ['isInsuranceTaken' => $isInsuranceTaken, 'user' => $viewParameter['user'], 'id' => $id, 'data' => $viewParameter['data'], 'pdf' => 1, 'signed_data' => $signed_data, 'lender' => $viewParameter['lender'], 'combined_sl_la' => $viewParameter['combined_sl_la']];
            $loanAgreement = (new ConsumerDocument(new Request()))->getABFLSigningDocument($id, $save_agreement_document_details);
            $pdf = $loanAgreement['pdf'];
            //$pdf->loadView('admin.documents.abfl.combine_loan_agreement', ['isInsuranceTaken' => $isInsuranceTaken, 'user' => $viewParameter['user'], 'id' => $id, 'data' => $viewParameter['data'], 'pdf' => 1, 'signed_data' => $signed_data, 'lender' => $viewParameter['lender'], 'combined_sl_la' => $viewParameter['combined_sl_la']])->setOption('encoding', 'UTF-8')->setPaper('a4')->setOrientation('portrait');
        } elseif($consumer_application_elements->is_bnpl) {
            $save_agreement_document_details = ['isInsuranceTaken' => $isInsuranceTaken, 'user' => $viewParameter['user'], 'id' => $id, 'data' => $viewParameter['data'], 'pdf' => 1, 'signed_data' => $signed_data, 'lender' => $viewParameter['lender'], 'combined_sl_la' => $viewParameter['combined_sl_la'], 'application' => $viewParameter['application']];
            $pdf->loadView('admin.documents.bnpl.service_agreement', $save_agreement_document_details)->setOption('encoding', 'UTF-8')->setPaper('a4')->setOrientation('portrait');
        }elseif(isset($viewParameter['lender']->id) && ($viewParameter['lender']->id == JMServices::$lender_id)){
            $save_agreement_document_details = ['isInsuranceTaken' => $isInsuranceTaken, 'user' => $viewParameter['user'], 'id' => $id, 'data' => $viewParameter['data'], 'pdf' => $system ? 0 : 1, 'signed_data' => $signed_data, 'lender' => $viewParameter['lender'], 'combined_sl_la' => $viewParameter['combined_sl_la'], 'application' => $viewParameter['application']];
            $pdf->setOption('header-html', (new ConsumerDocument(new Request()))->getPDFHeaderView());
            $pdf->loadView('admin.documents.jm.loan_agreement_v2', $save_agreement_document_details)->setOption('encoding', 'UTF-8')->setPaper('a4')->setOrientation('portrait');
        }elseif(isset($viewParameter['lender']->id) && ($viewParameter['lender']->id == Utkarsh::$lender_id)){
            $save_agreement_document_details = ['isInsuranceTaken' => $isInsuranceTaken, 'user' => $viewParameter['user'], 'id' => $id, 'data' => $viewParameter['data'], 'pdf' => $system ? 0 : 1, 'signed_data' => $signed_data, 'lender' => $viewParameter['lender'], 'combined_sl_la' => $viewParameter['combined_sl_la'], 'application' => $viewParameter['application']];
            $pdf->setOption('header-html', (new ConsumerDocument(new Request()))->getPDFHeaderView(Utkarsh::$lender_id));
            $pdf->loadView('admin.documents.utkarsh.loan_agreement_v3', $save_agreement_document_details)->setOption('encoding', 'UTF-8')->setPaper('a4')->setOrientation('portrait');
        }elseif(isset($viewParameter['lender']->id) && ($viewParameter['lender']->id == LendBox::$lender_id || $viewParameter['lender']->id == LendBoxLSP::$lender_id)){
            $save_agreement_document_details = ['isInsuranceTaken' => $isInsuranceTaken, 'user' => $viewParameter['user'], 'id' => $id, 'data' => $viewParameter['data'], 'pdf' => $system ? 0 : 1, 'signed_data' => $signed_data, 'lender' => $viewParameter['lender'], 'combined_sl_la' => $viewParameter['combined_sl_la'], 'application' => $viewParameter['application']];
            $pdf->loadView('admin.documents.lendbox.borrower_agreement', $save_agreement_document_details)->setOption('encoding', 'UTF-8')->setPaper('a4')->setOrientation('portrait');
        }elseif(isset($viewParameter['lender']->id) && ($viewParameter['lender']->id == Vivriti::$lender_id)){
            $save_agreement_document_details = ['isInsuranceTaken' => $isInsuranceTaken, 'user' => $viewParameter['user'], 'id' => $id, 'data' => $viewParameter['data'], 'pdf' => $system ? 0 : 1, 'signed_data' => $signed_data, 'lender' => $viewParameter['lender'], 'combined_sl_la' => $viewParameter['combined_sl_la'], 'application' => $viewParameter['application']];
            $pdf->loadView('admin.documents.vivriti.loan_agreement_v2', $save_agreement_document_details)->setOption('encoding', 'UTF-8')->setPaper('a4')->setOrientation('portrait');
        }elseif(isset($viewParameter['lender']->id) && $viewParameter['lender']->id == ConsumerApplication::AVANSE_LENDER_ID){
            $cDocObj =  new ConsumerDocument(new Request([]));
            $agreement =  $cDocObj->getSanctionLetterAndLoanAgreement($id, $signed_data);
            //$this->uploadToS3(str_replace(' ','_',strtolower($type)), $id, $agreement['pdf']->output());
            $this->uploadToS3(str_replace(' ','_',strtolower($type)), $id, $agreement['pdf']->output());
            return $agreement['pdf'];
        }elseif(isset($viewParameter['lender']->id) && ($viewParameter['lender']->id == KMGP2P::$lender_id)){
            $save_agreement_document_details = ['isInsuranceTaken' => $isInsuranceTaken, 'user' => $viewParameter['user'], 'id' => $id, 'data' => $viewParameter['data'], 'pdf' => $system ? 1 : 0, 'signed_data' => $signed_data, 'lender' => $viewParameter['lender'], 'combined_sl_la' => $viewParameter['combined_sl_la'], 'application' => $viewParameter['application']];
            $pdf->loadView('admin.documents.kmgp2p.borrower_agreement', $save_agreement_document_details)->setOption('encoding', 'UTF-8')->setPaper('a4')->setOrientation('portrait');
        }else {

            if ($consumer_application_elements->agreement_version == 2) {
                if ($viewParameter['lender']->id == 2) {
                    $save_agreement_document_details = ['isInsuranceTaken' => $isInsuranceTaken, 'user' => $viewParameter['user'], 'id' => $id, 'data' => $viewParameter['data'], 'pdf' => 1, 'signed_data' => $signed_data, 'lender' => $viewParameter['lender'], 'combined_sl_la' => $viewParameter['combined_sl_la']];
                    $pdf->loadView('admin.documents.borrower_loan_agreement_esign_v_two_v2', $save_agreement_document_details)->setOption('encoding', 'UTF-8')->setPaper('a4')->setOrientation('portrait');
                }else{
                    $save_agreement_document_details = ['isInsuranceTaken' => $isInsuranceTaken, 'user' => $viewParameter['user'], 'id' => $id, 'data' => $viewParameter['data'], 'pdf' => 1, 'signed_data' => $signed_data, 'lender' => $viewParameter['lender'], 'combined_sl_la' => $viewParameter['combined_sl_la']];
                    $pdf->loadView('admin.documents.borrower_loan_agreement_esign_v_two', $save_agreement_document_details)->setOption('encoding', 'UTF-8')->setPaper('a4')->setOrientation('portrait');
                }
            } else {
                $save_agreement_document_details = ['isInsuranceTaken' => $isInsuranceTaken, 'user' => $viewParameter['user'], 'id' => $id, 'data' => $viewParameter['data'], 'pdf' => 1, 'signed_data' => $signed_data, 'lender' => $viewParameter['lender'], 'combined_sl_la' => $viewParameter['combined_sl_la']];
                $pdf->loadView('admin.documents.borrower_loan_agreement_esign', $save_agreement_document_details)->setOption('encoding', 'UTF-8')->setPaper('a4')->setOrientation('portrait');
            }
        }
        $pdf->setOption("footer-right", "Page [page] from [topage]");
        $pdf->setOption('footer-font-size',10);
        $pdf->setOption('margin-bottom', 30);
        $pdf->setTemporaryFolder(storage_path().'/')->setOption('enable-local-file-access', true);
        $pdf->setOption('footer-html', view('admin.editor.footer',['type'=>$type,'lender'=> $viewParameter['lender'], 'user' => $viewParameter['user'], 'signed_data' => $signed_data])->render());

        $file = $pdf->output();
        if ($isInsuranceTaken) {
            /*$consumerDocument = new ConsumerDocument(new Request());
            $file = $consumerDocument->getInsuranceDocuments($id, $pdf, $viewParameter['user']['insurance_kotak_file']);*/
        }

        $file_id = $this->uploadToS3(str_replace(' ','_',strtolower($type)), $id, $file);

        (new ConsumerDocument((new Request())))->saveDocumentDetails($id, $file_id, 'LOAN_AGREEMENT', $save_agreement_document_details);

        return $file;
    }

    public function getSlackAttachmentText($data){
        $callback_id = $data['original_message']['attachments'][0]['callback_id'];
        return '';
    }

    public function pure_fields_values($data){
        return isset($data['original_message']['attachments'][0]['fields']) ?
            $data['original_message']['attachments'][0]['fields'] : array();
    }

    public function getNameOfResponder($name,$data,$text,$callback_service){

        switch($name){
            case 'acknowledge':
                $_text = $text."\n";
                $_text .= ' This request is acknowledge by !@';
                $_text .= $data['user']['id'];
                $text =  $this->getSlackAttachmentText($data);
                return ($text) ? $text : $_text;
                break;
            case 'mark_resolved':
                $_text = $text."\n";
                $_text .= ' This request is marked resolved by !@';
                $_text .= $data['user']['id'];
                $text = $this->getSlackAttachmentText($data);
                return ($text) ? $text : $_text;
                break;
            default :
                return 'Something went wrong';
                break;
        }
    }

    public function slackMessageService(Request $request){

            $response = $request->all();

            $data = json_decode($response['payload'],1);

            $name = isset($data['actions'][0]['value']) ? $data['actions'][0]['value'] : '';

            $title = ($data['original_message']['text']) ? $data['original_message']['text'] : (isset($data['original_message']['attachments'][0]['title']) ? $data['original_message']['attachments'][0]['title'] : '');
            $text = isset($data['original_message']['attachments'][0]['text']) ? $data['original_message']['attachments'][0]['text'] : '';
            $message_ts = isset($data['message_ts']) ? $data['message_ts'] : 0;
            $action_ts = isset($data['action_ts']) ? $data['action_ts'] : 0;

            $callback_id = isset($data['callback_id']) ? $data['callback_id'] : 0;
            $callback_service = '';
            if (strpos($callback_id, '|') !== false) {
                $_callback_id = explode('|',$callback_id);
                $callback_id = (isset($_callback_id[0])) ? $_callback_id[0] : $callback_id;
                $callback_service = (isset($_callback_id[1])) ? $_callback_id[1] : $callback_id;
            }

            $message = array(
                'channel' => '',
                'attachment_title' => $title,
                'attachment_text' => $this->getNameOfResponder($name,$data,$text,$callback_service),
                'response_url' => $data['response_url'],
                'replace_original'=> true,
                'text' => $title,
                'response_type'=> 'in_channel',
                'pure_fields_values' => ($fields = $this->pure_fields_values($data)) ? $fields : array(),
                'pure_fields' => ($fields) ? true : false,
                'isBot' => true
            );

            if($callback_id && $message_ts) {
                /*Actions::setMicroAction([
                    'service' => 'slack',
                    'message_ts' => $message_ts,
                    'action_ts' => $action_ts,
                    'type' => $callback_id
                ]);*/
            }

        (new _Slack(new Request($message)))->connect();
    }

    public function uploadToS3($file_type, $id, $file,$ismerchant = 0){
        if($ismerchant == 0) {
            $file_path = '/' . $id . '/' . $file_type . '.pdf';
            $file_path_name = '/' . $id . '/' . $file_type . '.pdf' . '/' . $file_type . '.pdf';
        }else{
            $file_path = '/merchant/' . $id . '/' . $file_type . '.pdf';
            $file_path_name = '/merchant/' . $id . '/' . $file_type . '.pdf' . '/' . $file_type . '.pdf';
        }
        $s3 = Storage::disk('s3');
        if ($file) {
            $s3->put($file_path_name, $file);
            $ConsumerApplication = new ConsumerApplicationController();
            $data['file_type'] = $file_type;
            $data['id'] = $id;
            $data['ismerchant'] = $ismerchant;
            return $ConsumerApplication->getUploadedFileNameMultiple($s3, $file_path,$data);
//            $file_path = $ConsumerApplication->getUploadedFileName($s3, $file_path);
//
//            if ($s3) {
//                if($ismerchant == 0) {
//                    $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->file_path = $file_path;
//                    $consumer_application_file->save();
//                }else{
//                    $consumer_application_file = new MerchantFiles();
//                    $consumer_application_file->merchant_id = $id;
//                    $consumer_application_file->file_type = $file_type;
//                    $consumer_application_file->file_path = $file_path;
//                    $consumer_application_file->save();
//                }
//            $file_url = "https://s3.ap-south-1.amazonaws.com/creditfair-customer-documents/".$file_path;
//            $s3->setVisibility($file_path, 'public');
//            return $file_url;
//            }
        }

    }

    public function get_client_ip() {
        $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';

        return $ipaddress;
    }

    public function showThankYouScreen(){
        return view('front.thank-you');
    }

    public function redirectPageforConsumerApp(Request $request){
        $data['state'] = $request->query('state');
        return view('front.consumer_app_acct_aggr', $data);
    }

    public function fetchBankStatement(Request $request){
        $application_id = $request->query('application_id');
        $hashids = new Hashids('Creditfair by CS', 20);
        $application_hashed_id = $hashids->encode($application_id);
        $data['application_id'] = $application_hashed_id;
        $data['source'] = $request->query('source');
        $data['merchant_sse'] = $request->query('merchant_sse');
        $data['raw_application_id'] = $application_id;
        return view('front.bank_statement', $data);
    }

    public function esignupdate(Request $request,$hashed_id){
        $hashid = explode("_",$hashed_id);
        $hashids         = new Hashids('Creditfair by CS', 20);
        $application_ids = $hashids->decode($hashid[1]);
        $id = $application_ids[0];
        $type = "Loan Agreement Esign";
        $data=$request->all();
        $state = json_decode($data['state']);
        if(isset($state->error)){
            return view('front.esign-failure', $data);
        }
        $file = file_get_contents($state->documents[0]->documentURL);
        $this->uploadToS3(str_replace(' ','_',strtolower($type)), $id, $file,1);

        $data = array("application_ids" => $id);
        $transaction_id= $state->transactionId;
        $secureKey = _env('MANCHSECUREKEY');
        $organizationKey = _env('MANCHORGANIZATIONKEY');
        $url = _env('MACHURL')."api/get-transaction-status";
        $manch_data = json_encode(array("secureKey"=>$secureKey,"organizationKey"=>$organizationKey,"transactionId"=>$transaction_id));
            $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => $url,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => "",
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => "POST",
                CURLOPT_POSTFIELDS => $manch_data,
                CURLOPT_HTTPHEADER => array(
                    "Content-Type: application/json"
                ),
            ));

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

            curl_close($curl);

            if($response){
                $response = json_decode($response);
                if(isset($response->documents[0]->signerInfo)){
                    $name = $response->documents[0]->signerInfo[0]->commonName;
                    $addhar_number = $response->documents[0]->signerInfo[0]->title;
                }
            }
        $data['fees'] = $this->getFeesData($id);
        return view('front.esign-congrats', $data);
    }
    public function partnerQuery(Request $request){

        $data = $request->all();

        try {
            $partner = [
                'name' => isset($data['name']) ? $data['name'] : '',
                'contact' => isset($data['number']) ? $data['number'] : '',
                'email' => isset($data['email']) ? $data['email'] : '',
                'company_name' => isset($data['company_name']) ? $data['company_name'] : '',
                'turnover' => isset($data['turnover']) ? $data['turnover'] : '',
                'website' => isset($data['website']) ? $data['website'] : '',
                'existing_partner' => (isset($data['other_financial']) && $data['other_financial'] == 'Yes') ? 1 : 0,
                'merchant' => isset($data['existing_partner']) ? $data['existing_partner'] : '',
                'industry' => isset($data['industry']) ? $data['industry'] : '',
                'reference' => isset($data['come_to_know']) ? $data['come_to_know'] : '',
                'refer_code' => isset($data['referee']) ? $data['referee'] : '',
            ];

            Partners::insert($partner);


            if($partner['email']) {
                \Mail::send('emails.new_merchant', [
                    'user' => $data
                ], function ($message) use ($data) {
                    $message->to('bd@creditfair.in')->subject('Become A Brand Partner - Registration');
                });
            }
        }catch (\Exception $e){
            \Session::flash('success', 'Something went wrong went, Please try again later.');
        }

        \Session::flash('success', 'Your request has been processed');
        return redirect()->back();
    }

    public function enach($id){
        $hashids         = new Hashids('Creditfair by CS', 20);
        $application_ids = $hashids->decode($id);
        $bankdata = Bank::where('application_id',$application_ids[0])->get();
        if(count($bankdata) > 0){
            $mandate = Mandate::where('consumer_application_id',$application_ids[0])->get();
            if(count($mandate) > 0){
                foreach($mandate as $mandateDetails){
                    if($mandateDetails->status == 'submitted' || $mandateDetails->status == 'pending'){
                        $return_url = asset("enach/id/".$id);
                        return redirect()->to($return_url);
                    }elseif($mandateDetails->status == 'active'){
                        return redirect()->to($mandateDetails->mandate_id);
                    }else{
                        $ConsumerDocument = New ConsumerDocument(New Request());
                        $manduateurl = $ConsumerDocument->createenach($application_ids[0]);
                        return redirect()->to($manduateurl);
                    }
                }
            }
        }
        $data = array();
        $data['is_home'] = true;
        $data['bank_names_list'] = array_keys(Config::get('constants.emandate_bank_list'));
        $data['application_ids'] = $application_ids[0];
        return view('front.bankdetails',$data);
    }

    public function directenachQuery($en_data){
        //echo "<pre>";print_r($en_data);die;
        $req_base_1 = json_decode($en_data['req_base'],1);
        $req_base = array();
        $data = array();
        $hashids = new Hashids('Creditfair by CS', 20);
        $data['b_type'] = $hashids->decode($req_base_1['b_type'])[0];
        $data['emandate_variant'] = $en_data['emandate_variant'];
        $data['req_base'] = $en_data['req_base'];
        $data['applicationid'] = $en_data['application_ids'];
        $frequency = isset($data['b_type']) && $data['b_type'] == 0 ? 'monthly' : 'ADHO';
        $emandate_variant = isset($data['emandate_variant']) && $data['emandate_variant'] ? $data['emandate_variant'] : 'emandate';
        $until_cancelled = 0;
        if (isset($data['b_type']) && $data['b_type'] == 2){
            $until_cancelled = 1;
        }

        $nach = new NachController();
        $nach->until_cancelled = $until_cancelled;
        $nach->retry_nach = isset($data['revised_link']);
        $nach->app_type = (Input::has('app_type') && Input::get('app_type') == 2) ? Input::get('app_type') : '1';
        $nachresponse = json_decode($nach->createMandate($data['applicationid'],$emandate_variant,$frequency));

        if(isset($nachresponse->url) && $nachresponse->url != "") {
            return redirect()->to($nachresponse->url);
        }else{
            $bank_names_array = Config::get('constants.emandate_bank_list');
            $bank_names_list = array_keys($bank_names_array);
            $response = array();
            $response['is_home'] = true;
            $response['application_ids'] = $en_data['application_ids'];
            $response['bank'] = $en_data;
            $response['bank_names_list'] = $bank_names_list;

            $string = '';
            if (isset($nachresponse->error->param) && $nachresponse->error->param == 'nach_debit.reference1'){
                $string = 'Invalid Account Number';;
            }

            $param = isset($nachresponse->error->error->param) ? ucfirst(str_replace('.',' ',str_replace('_',' ',$nachresponse->error->error->param.' '))) : '';
            $message = isset($nachresponse->error->error->message) ? $nachresponse->error->error->message: '';

            $response['isRetry'] = false;
            if($message == 'Amount must be between Rs 1.0 and Rs 100000.0'){
                $response['isRetry'] = true;
            }

            $response['error'] = $message || $string || $param ? ($string ? $string : $param.$message) : 'Something went wrong went, Please try again later.';
            $response['b_type_status'] = $frequency;
            $req_base = json_decode($data['req_base'], 1);
            $nach->error_message = $response['error'];
            $nach->retry_nach = $response['isRetry'];
            if(!empty($response['error'])){
                $nach->display = 1;
            }
            $nach->app_type = (Input::has('app_type') && Input::get('app_type') == 2) ? Input::get('app_type') : '';
            return $nach->addEMandateConsumner($req_base['id'], $req_base['b_type'], $req_base['emandate_variant']);
            //return view('front.bankdetails',$response);
        }
    }

    public function vkycProcessUpdate($hashed_id, $applicant_type_hashed_id){
        return view('front.thank-you', ['hashed_id' => $hashed_id, 'applicant_type' => $applicant_type_hashed_id]);
    }

    public function bankValidation($requestBody) {
        $data = $requestBody;
        $app_type = isset($data['type']) ? $data['type'] : "1";
        $bank = Bank::where(['application_id' => $data['applicationid'], 'applicant_type' => $app_type])->first(['id', 'account_number', 'karza_response']);
        $bankSuccess = false;
        if (isset($bank->id)) {
            $validation = isset($bank->karza_response) ? json_decode($bank->karza_response) : null;
            if (isset($validation->result->bankResponse) && $validation->result->bankResponse == 'SUCCESSFUL TRANSACTION') {
                $bankSuccess = true;
            } else {
                if (isset($validation) && isset($validation->result->bankResponse) && $validation->result->bankResponse != 'SUCCESSFUL TRANSACTION') {
                    Input::merge(['re_validate' => 'on']);
                }
                $consumerApplicationController = new ConsumerApplicationController();
                Input::merge([
                    'applicant_type' => $app_type,
                    'application_id' => $data['applicationid'],
                    'name' => $data['name'],
                    'account_type' => $data['accounttype'],
                    'bank_name' => $data['bankname'],
                    'branch_name' => $data['branch'],
                    'account_number' => $data['accountno'],
                    'ifsc_code' => $data['ifsccode']
                ]);
                $response = $consumerApplicationController->storeBankDetails($data['applicationid'], false);
                $response = $response->getData();
                if (isset($response) && $response->message == 'SUCCESSFUL TRANSACTION') {
                    $bankSuccess = true;
                }
            }
        } else {
            $consumerApplicationController = new ConsumerApplicationController();
            Input::merge([
                'applicant_type' => $app_type,
                'application_id' => $data['applicationid'],
                'name' => $data['name'],
                'account_type' => $data['accounttype'],
                'bank_name' => $data['bankname'],
                'branch_name' => $data['branch'],
                'account_number' => $data['accountno'],
                'ifsc_code' => $data['ifsccode']
            ]);
            $response = $consumerApplicationController->storeBankDetails($data['applicationid'], false);
            $response = $response->getData();
            if (isset($response) && $response->message == 'SUCCESSFUL TRANSACTION') {
                $bankSuccess = true;
            }
        }
        return $bankSuccess;
    }

    public function enachQuery($postApproval=true){

        $data = Input::all();
        $hashids = new Hashids('Creditfair by CS', 20);
        $app_type = isset($data['type']) ? $data['type'] : "1";

        if ($postApproval) {
            $bankValidationStatus = $this->bankValidation($data);
        }

        if ($app_type == "2") {
            if($bankValidationStatus) {
                $hashedAppID = $hashids->encode($data['applicationid']);
                return redirect()->to('esign/' . $hashedAppID . '?type=' . $app_type);
            }
        }

        // Bank validation added to post approval process
        if (!$postApproval || $bankValidationStatus) {
            $frequency = isset($data['b_type']) && $data['b_type'] == 0 ? 'monthly' : 'ADHO';
            $emandate_variant = isset($data['emandate_variant']) && $data['emandate_variant'] ? $data['emandate_variant'] : 'emandate';
            $until_cancelled = 0;
            if (isset($data['b_type']) && $data['b_type'] == 2){
                $until_cancelled = 1;
            }

            try {
                $bankid = isset($data['bankid']) ? $data['bankid'] : '';
                $bank_name = isset($data['bankname']) ? $data['bankname'] : '';
                $bank_ifsc_code = "";
                $bank_names_array = Config::get('constants.emandate_bank_list');
                $bank_names_list = array_keys($bank_names_array);

                if(in_array($bank_name ,$bank_names_list)) {
                    $bank_ifsc_code = $bank_names_array[$bank_name];
                }
                if($bank_name == "Equitas Small Finance Bank"){
                    $bank_ifsc_code = "ESFB";
                }
                if($bank_name == "HDFC Bank"){
                    $bank_ifsc_code = "HDFC";
                }
                if($bank_name == "ICICI Bank"){
                    $bank_ifsc_code = "ICIC";
                }
                if($bank_name == "IDBI Bank"){
                    $bank_ifsc_code = "IBKL";
                }
                if($bank_name == "Indian Overseas Bank"){
                    $bank_ifsc_code = "IOBA";
                }
                if($bank_name == "Tamilnad Mercantile Bank"){
                    $bank_ifsc_code = "TMBL";
                }
                if($bank_name == "Ujjivan Small Finance Bank"){
                    $bank_ifsc_code = "USFB";
                }

                $bankdetails = [
                    'name' => isset($data['name']) ? $data['name'] : '',
                    'ifsc_code' => isset($data['ifsccode']) ? $data['ifsccode'] : '',
                    'bank_name' => $bank_name,
                    'branch_name' => isset($data['branch']) ? $data['branch'] : '',
                    'account_number' => isset($data['accountno']) ? $data['accountno'] : '',
                    'account_type' => isset($data['accounttype']) ? $data['accounttype'] : '',
                    'application_id' => isset($data['applicationid']) ? $data['applicationid'] : '',
                    'bank_ifsc_code' => $bank_ifsc_code,
                ];

                $nach = new NachController();
                $nach->until_cancelled = $until_cancelled;
                $nach->retry_nach = isset($data['revised_link']);
                $nach->app_type = (Input::has('app_type') && Input::get('app_type') == 2) ? Input::get('app_type') : '';
                // if($data['lenderid'] == 11){
                //     $nachresponse = json_decode($nach->createMandateFromTransbnk($data['applicationid'],$emandate_variant,$frequency,$until_cancelled));
                // }else{
                    $nachresponse = json_decode($nach->createMandate($data['applicationid'],$emandate_variant,$frequency,$until_cancelled));

                if(isset($nachresponse->url) && $nachresponse->url != "") {
                    return redirect()->to($nachresponse->url);
                }else{
                    $response = array();
                    $response['is_home'] = true;
                    $response['application_ids'] = $data['applicationid'];
                    $response['bank'] = $data;
                    $response['bank_names_list'] = $bank_names_list;

                    $string = '';
                    if (isset($nachresponse->error->param) && $nachresponse->error->param == 'nach_debit.reference1'){
                        $string = 'Invalid Account Number';;
                    }

                    $param = isset($nachresponse->error->error->param) ? ucfirst(str_replace('.',' ',str_replace('_',' ',$nachresponse->error->error->param.' '))) : '';
                    $message = isset($nachresponse->error->error->message) ? $nachresponse->error->error->message: '';

                    $response['isRetry'] = false;
                    if($message == 'Amount must be between Rs 1.0 and Rs 100000.0'){
                        $response['isRetry'] = true;
                    }

                    $response['error'] = $message || $string || $param ? ($string ? $string : $param.$message) : 'Something went wrong went, Please try again later.';
                    $response['b_type_status'] = $frequency;
                    $req_base = json_decode($data['req_base'], 1);
                    $nach->error_message = $response['error'];
                    $nach->retry_nach = $response['isRetry'];
                    $nach->app_type = (Input::has('app_type') && Input::get('app_type') == 2) ? Input::get('app_type') : '';
                    return $nach->addEMandateConsumner($req_base['id'], $req_base['b_type'], $req_base['emandate_variant']);
                }

            }catch (\Exception $e){
                (new Slack(new Request(['title' => 'Mandate Access Error', 'fields' => ['error' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString()], 'group' => Slack::$STAGE_TESTING])))->send();
                $response = array();
                $response['is_home'] = true;
                $response['application_ids'] = $data['applicationid'];
                $response['lender_ids'] = $data['lenderid'];
                $response['bank'] = $data;
                $bank_names_array = Config::get('constants.emandate_bank_list');
                $bank_names_list = array_keys($bank_names_array);
                $response['bank_names_list'] = $bank_names_list;
                $param = isset($nachresponse->error->error->param) ? ucfirst(str_replace('.',' ',str_replace('_',' ',$nachresponse->error->error->param.' '))) : '';
                $response['error'] = isset($nachresponse->error->error->message) ? $response.' '.$nachresponse->error->error->message : 'Something went wrong went, Please try again later.';
                $response['b_type_status'] = $frequency;
                $response['app_type'] = (Input::has('app_type') && Input::get('app_type') == 2) ? Input::get('app_type') : '';
                return view('front.bankdetails',$response);
            }
        }
        $response = array();
        $response['is_home'] = true;
        $response['application_ids'] = $data['applicationid'];
        $response['lender_ids'] = $data['lenderid'];
        $response['bank'] = $data;
        $bank_names_array = Config::get('constants.emandate_bank_list');
        $bank_names_list = array_keys($bank_names_array);
        $response['bank_names_list'] = $bank_names_list;
        $param = '';
        $response['b_type_status'] = '';
        $response['error'] = 'Bank validation failed. Please try again.';
        $response['app_type'] = '?type='.$app_type;
        return view('front.bankdetails',$response);
    }

    public function licence(){
        $data = '<!-- 7a9ade0256e46b1e3ad0fa8666efbb5d36c35c991e353367c566e06d90e06d21eade052c79d0ce7798edc5a9ddc38bb8500de022e9a5b5352edc70d763473f01 -->
        <ObtainTicketResponse><message></message><prolongationPeriod>607875500</prolongationPeriod><responseCode>OK</responseCode><salt>1539406229350</salt><ticketId>1</ticketId><ticketProperties>licensee=QiQi	licenseType=0	</ticketProperties></ObtainTicketResponse>';
        return response($data, 200, [
        'Content-Type' => 'text/plain'
        ]);
    }

    public function getconsentmessage($language,$lender_id){
        $lender_consent = LenderLanguageConsent::where('language',$language)->where('lender_id',$lender_id)->where('status',1)->first(['consent']);
        if($lender_consent){
            return $lender_consent['consent'];
        }else{
            return "I have been read out and explained in the language known to me, the contents of the loan documents and all other documents incidental to availing the loan from K. M. Global Credit Private Limited and I have signed the said documents after having understood them and by signing the same I do hereby agree to abide by all the general terms and conditions of the loan and the articles of the same.";
        }
    }

    public function viewFile($id,$document_type,$path = ''){
        $hashids         = new Hashids('Creditfair by CS', 20);
        $application_ids = $hashids->decode($id);
        $application_id = $application_ids[0];
        $document = base64_decode($document_type);
        if($path) {
            $file_path = base64_decode($path);
        }

        $files = ConsumerApplicationFiles::where("consumer_application_id",$application_id)->where('file_type',$document);
        if(isset($file_path)) {
            $files = $files->where('file_path', $file_path);
        }
        $files = $files->orderBy('id','desc')->first(['file_path']);
        if($files) {
            $s3 = Storage::disk('s3');
            $path = storage_path().'/'.time().'.pdf';
            $view = $s3->get($files['file_path']);
            $file = fopen($path, "w");
            fwrite($file, $view);
            fclose($file);
            return response()->file($path)->deleteFileAfterSend(true);
        }
    }

    public function viewDocuments($id){
        $hashids                = new Hashids('Creditfair by CS', 20);
        $application_id_hashed = $hashids->decode($id);
        $application_id = isset($application_id_hashed[0]) ? $application_id_hashed[0] : 0;
        //$application_id = $id;
        $documents = [];
        $applications = ConsumerApplication::with(['documents'=> function ($query){
            $query->whereIn('file_type',['sanction_letter','agreement','loan_agreement_esign','welcome_letter','Processing Fee Invoice','recall_notice']);
        },'emi'])->where('id',$application_id)->first();
        $application_id_hashed = $hashids->encode($application_id);
        $s3 = Storage::disk('s3');
        if($applications->documents) {
            foreach ($applications->documents as $application) {
                if(strpos($application->file_path,'.pdf') !== false || strpos($application->file_path,'.jpg') || strpos($application->file_path,'.png') !== false) {
                    $name = $application->file_type;
                    $processingFee = ($name == 'Processing Fee Invoice') ? $this->isProcessingFee($applications) : '';
                    $status = $this->getDocumentStatus($application, $processingFee);
                    //$s3->setVisibility($application->file_path, true);
                    $path = strpos($application->file_path, 'cloudinary') !== false ? $application->file_path : /*'https://s3.'._env('AWS_DEFAULT_REGION').'.amazonaws.com/'._env('AWS_BUCKET').'/'.$application->file_path;*/'/documents/' . $application_id_hashed . '/' . base64_encode($application->file_type).'/'.base64_encode($application->file_path);
                    $documents[ucwords(str_replace('_',' ',$name))] = [
                        'id' => $application->id,
                        'type' => $status->type,
                        'message' => $status->message,
                        'document' => $path,
                        'description' => '',
                        'created_at' => date('d M, Y', strtotime($application->created_at)),
                        'isPDF' => (strpos($application->file_path, '.pdf') !== false) ? true : false,
                        'is_reviewed' => $application->is_reviewed,
                        'is_processing_fee' => $processingFee
                    ];
                }
            }
        }
        $data['documents'] = $documents;
        return view('front.documents', $data);
    }

    public function isProcessingFee($process){

        $isProcessingFeeReceived = OnlinePayment::where('application_id', $process->id)
            ->where('purpose','processing_fee')
            ->where('status','paid')->first(['id']);

        if(!isset($isProcessingFeeReceived->id)) {
            $consumerDocument = new ConsumerDocument(new Request(['bot' => true]));
            $response = $consumerDocument->getDocument($process->id);
            return isset($response['user']['processing_fee_link']) && !empty($response['user']['processing_fee_link']) ? $response['user']['processing_fee_link'] : '';
        }
        return 1;
    }

    public function getDocumentStatus($application, $processingFee){
        $status = new \stdClass();
        if($application->file_type == 'Processing Fee Invoice'){
            $status->type = ($processingFee == 1) ? 1 : 2;
            $status->message = ($processingFee == 1) ? 'Paid' : 'Not Paid';
        }else{
            $status->type = ($application->is_reviewed) ? 1 : 2;
            $status->message = ($application->is_reviewed) ? 'Reviewed' : 'Not Reviewed';
        }
        return $status;
    }

    public function getPayments($id){


        $application = ConsumerApplication::with([
            'merchant' => function($query){
                return $query->select('id','merchant_name');
            }, 'application_element' => function($query){
                return $query->select('id','application_id','product_name', 'total_amount_due', 'emi_paid', 'emi_pending', 'amount_over_due');
            }, 'proFormaInvoice' => function($query){
                return $query->select('id','application_id','loan_application_no', 'created_at');
            }, 'emi' => function($query){
                return $query->select('application_id','upfront_from_customer', 'remaining_emi', 'tenure','interest_rate', 'processing_fee');
            }, 'emi.offer' => function($query){
                return $query->select('id','processing_fee_first_emi');
            },
            'category' => function($query){
                return $query->select('id','name');
            }, 'foreclosed_transaction'
        ])->where('id', $id)->first(['id', 'created_at','lender_id', 'merchant_id', 'purpose', 'approved_amount', 'state']);

        $processing_fee = 0;
        $isForeclosed = 0;
        $adhoc_payment = 0;


        $overpayments = PaymentTransaction::on('mysql_readonly')->where('application_id',$id)->whereIn('payment_for',['processing_fee', 'Foreclosure', 'Over Payment', 'Advance Payment'])->whereNull('is_deleted_at')->get(['amount', 'status', 'payment_for']);


        foreach ($overpayments as $overpayment) {
            if ($overpayment->amount > 0 && ($overpayment->payment_for == "processing_fee")) {
                $processing_fee = $processing_fee + $overpayment->amount;
            }
            if ($overpayment->amount > 0 && ($overpayment->payment_for == "Foreclosure") && $overpayment->status != "rejected"){
                $isForeclosed = 1;
            }
            if ($overpayment->amount > 0 && ($overpayment->payment_for == "Over Payment" || $overpayment->payment_for == "Advance Payment" || $overpayment->payment_for == "Foreclosure") && $overpayment->status != "rejected") {
                $adhoc_payment = $adhoc_payment + $overpayment->amount;
            }
        }



        $accountingController = new AccountingController();
        $loan_management = new LoanManagement();

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

        $foreclosure_data = $loan_management->getForeclosureAmount($id);
        $foreclosure_amount = (isset($foreclosure_data['total_outstanding'])) ? $foreclosure_data['total_outstanding'] : 0;
        if($processing_fee_due > 0){
            $foreclosure_amount = $foreclosure_amount + $processing_fee_due;
        }

        $amount_paid = 0;
        if($application->emi_payment) {
            foreach ($application->emi_payment as $emi_payments) {
                $amount_paid = $amount_paid + ($emi_payments->total_payable - $emi_payments->amount_due);
            }
        }

        $amount_pending = $isForeclosed == 1 ? 0 : $application->application_element->total_amount_due;
        $amount_paid = $amount_paid + $adhoc_payment;
        $emi_paid = $application->application_element->emi_paid;
        $emi_due = $isForeclosed == 1 ? 0 : $application->application_element->emi_pending;
        $amount_due = $isForeclosed == 1 ? 0 : $application->application_element->amount_over_due;

        $isMoratorium = false;
        $consumerApplicationController = new ConsumerApplicationController();
        //$repaymentSchedule = $accountingController->viewloanschedule($id, 1);
        $repaymentSchedule = $loan_management->loan_schedule;


        $schedule = [];

        $lastTransaction = [];
        $pendingTransaction = [];
        $upcoming_date_set = 0;
        $now_date = Carbon::now();
        foreach ($repaymentSchedule['schedule'] as $key => $repayment) {

            $amount_received = 0;
            $payment_date = '';
            $payment_dates = [];
            $payment_mode = '';
            if (isset($repayment['transaction'])) {
                foreach ($repayment['transaction'] as $transaction) {
                    $amount_received += $transaction->amount;
                    $payment_date = $transaction->payment_date;
                    $payment_dates[] = strtotime($transaction->payment_date);

                    $payment_mode = $transaction->mode;
                }
            }
            $newDates = [];
            foreach ($payment_dates as $_key=>$date){
                $newDates[$_key] = $date;
            }
            array_multisort($newDates, SORT_DESC, $payment_dates);

            $index = ($key + 1);
            $previous_key = ($key - 1);


            $moratorium_amount = isset($repayment['moratorium_amount']) ? $repayment['moratorium_amount'] : 0;

            if($moratorium_amount){
                $isMoratorium = true;
            }

            if (isset($upcoming_date_set) && $upcoming_date_set == 0 && $now_date < $repayment['emi_date']) {
                $upcoming_due_date = $repayment['emi_date'];
                $upcoming_payment = [
                    'due_date' => $upcoming_due_date,
                    'installment_amount' => $repayment['amount']
                ];
                $upcoming_date_set = 1;
            }

            $scheduleData = [
                'id' => $index,
                'due_date' => date('d-M-Y', strtotime($repayment['due_date'])),
                'next_emi_word' => $this->getWordsFromInstallment($index),
                'opening_principal' => ($index == 1) ? (round(($repayment['principal_outstanding'] + $repayment['principal']), 2)) : (isset($repaymentSchedule['schedule'][$previous_key]) ? round($repaymentSchedule['schedule'][$previous_key]['principal_outstanding'], 2) : 0),
                'installment_amount' => $repayment['amount'] - $moratorium_amount,
                'principal' => round($repayment['principal'], 2),
                'interest' => round($repayment['interest'], 2),
                'closing_balance' => (round(($repayment['principal_outstanding']), 2)),
                'bounce' => $repayment['bounce_charges'],
                'penal' => $repayment['delay_penalty'],
                'charges_waived' => $repayment['charges_waived'],
                'total_due' => round(($repayment['amount'] + $repayment['bounce_charges'] + $repayment['delay_penalty']) - $repayment['charges_waived'], 2),
                'amount_received' => $amount_received,
                'payment_date' => date('d-M-Y', strtotime($payment_date)),
                'last_payment_date' => isset($payment_dates[0]) && count($payment_dates) > 0 ? $payment_dates[0] : $payment_date,
                'payment_mode' => $payment_mode,
                'moratorium_amount' => $moratorium_amount,
                'payment_status' => $repayment['payment_status']
            ];



            if(in_array($repayment['payment_status'], ['success','partial'])) {
                $lastTransaction[] = $scheduleData;
            }else{
                $pendingTransaction[] = $scheduleData;
            }


            $schedule[] = $scheduleData;
        }
        $hashids = new Hashids('Creditfair by CS', 20);
        $hashed_id = $hashids->encode($id);

        $disbursed_date = $consumerApplicationController->getDisbursedDate($application->id);
        if($disbursed_date) {
            $disbursed_date = date('d M Y', strtotime($disbursed_date));
        }

        $response = [
            'id' => $hashed_id,
            'created_at_date' => date('d M Y', strtotime($application->created_at)),
            'lender_id' => $application->lender_id,
            'merchant_id' =>$application->merchant_id,
            'category_id' =>$application->purpose,
            'customer_name' => $repaymentSchedule['customer_name'],
            'merchant_name' => $application->merchant->merchant_name,
            'amount_pending' => $amount_pending,
            'amount_paid' => $amount_paid,
            'emi_paid' => $emi_paid,
            'category_name' => ($application->category) ? $application->category->name : '',
            'disbursed_date' => $disbursed_date,
            'emi_due' => $emi_due,
            'amount_due' => $amount_due,
            'advance_amount' => $application->emi->upfront_from_customer,
            'total_emi' => $application->emi->tenure,
            'advance_emi' => ($application->emi->tenure - $application->emi->remaining_emi),
            'product' => isset($application->application_element) && !empty($application->application_element->product_name) ? $application->application_element->product_name : '',
            'agreement_no' => $application->proFormaInvoice && $application->proFormaInvoice->loan_application_no ? $application->proFormaInvoice->loan_application_no : '',
            'agreement_date' => date('d-m-Y', strtotime($application->proFormaInvoice->created_at)),
            'frequency' => 'Monthly',
            'amount_financed' => $application->approved_amount,
            'interest' => $application->emi->interest_rate,
            'tenure' => $application->emi->tenure,
            'processing_fee' => $application->emi->processing_fee,
            'processing_fee_first_emi' => isset($application->emi->offer->processing_fee_first_emi) ? $application->emi->offer->processing_fee_first_emi : 0,
            'remaining_emi' => $application->emi->remaining_emi,
            'status' => (in_array($application->state, ['disbursed', 'nach registered'])) ? 'Active' : 'Inactive',
            'schedule' => $schedule,
            'last_transaction' => isset($lastTransaction[count($lastTransaction) - 1]) ? $lastTransaction[count($lastTransaction) - 1] : '',
            'pending_transaction' => $pendingTransaction,
            'success_transaction' => $lastTransaction,
            'fore_closure_amount' => $foreclosure_amount,
            'account_statement' => asset('/consumer/account-statement/'.$id),
            'isMoratorium' => $isMoratorium,
            'isForeclosed' => (bool)$application->foreclosed_transaction,
            'upcoming_payment' => $upcoming_payment ?? []
        ];

        if(isset($application->foreclosed_transaction->id)){
            $response['foreclosedAmount'] =  $application->foreclosed_transaction->amount;
            $response['foreclosedMode'] =  $application->foreclosed_transaction->mode;
            $response['foreclosedDate'] =  $application->application_element->foreclosure_date;
        }

        return $response;

        return false;
    }

    public function getWordsFromInstallment($number){


        $numbers = [
            1 => 'First',
            2 => 'Second',
            3 => 'Third',
            4 => 'Fourth',
            5 => 'Fifth',
            6 => 'Sixth',
            7 => 'Seventh',
            8 => 'Eighth',
            9 => 'Ninth',
            10 =>'Tenth',
            11 =>'Eleventh',
            12 =>'Twelfth',
            13 =>'Thirteenth',
            14 =>'Fourteenth',
            15 =>'Fifteenth',
            16 =>'Sixteenth',
            17 =>'Seventeenth',
            18 =>'Eighteenth',
            19 =>'Nineteenth',
            20 =>'Twentieth',
            21 =>'Twenty-first',
            22 =>'Twenty-second',
            23 =>'Twenty-third',
            24 =>'Twenty-fourth',
            25 =>'Twenty-fifth',
            26 =>'Twenty-sixth',
            27 =>'Twenty-seventh',
            28 =>'Twenty-eighth',
            29 =>'Twenty-ninth',
            30 =>'Thirtieth',
            31 =>'Thirty-first',
            32 =>'Thirty-second',
            33 =>'Thirty-third',
            34 =>'Thirty-fourth',
            35 =>'Thirty-fifth',
            36 =>'Thirty-sixth',
            37 =>'Thirty-seventh',
            38 =>'Thirty-eighth',
            39 =>'Thirty-ninth',
            40 =>'Fortieth',
            41 =>'Forty-first',
            42 =>'Forty-second',
            43 =>'Forty-third',
            44 =>'Forty-fourth',
            45 =>'Forty-fifth',
            46 =>'Forty-sixth',
            47 =>'Forty-seventh',
            48 =>'Forty-eighth',
            49 =>'Forty-ninth',
            50 =>'Fiftieth',
            51 =>'Fifty-first',
            52 =>'Fifty-second',
            53 =>'Fifty-third',
            54 =>'Fifty-fourth',
            55 =>'Fifty-fifth',
            56 =>'Fifty-sixth',
            57 =>'Fifty-seventh',
            58 =>'Fifty-eighth',
            59 =>'Fifty-ninth',
            60 =>'Sixtieth',
            61 =>'Sixty-first',
            62 =>'Sixty-second',
            63 =>'Sixty-third',
            64 =>'Sixty-fourth',
            65 =>'Sixty-fifth',
            66 =>'Sixty-sixth',
            67 =>'Sixty-seventh',
            68 =>'Sixty-eighth',
            69 =>'Sixty-ninth',
            70 =>'Seventieth',
            71 =>'Seventy-first',
            72 =>'Seventy-second',
            73 =>'Seventy-third',
            74 =>'Seventy-fourth',
            75 =>'Seventy-fifth',
            76 =>'Seventy-sixth',
            77 =>'Seventy-seventh',
            78 =>'Seventy-eighth',
            79 =>'Seventy-ninth',
            80 =>'Eightieth',
            81 =>'Eighty-first',
            82 =>'Eighty-second',
            83 =>'Eighty-third',
            84 =>'Eighty-fourth',
            85 =>'Eighty-fifth',
            86 =>'Eighty-sixth',
            87 =>'Eighty-seventh',
            88 =>'Eighty-eighth',
            89 =>'Eighty-ninth',
            90 =>'Ninetieth',
            91 =>'Ninety-first',
            92 =>'Ninety-second',
            93 =>'Ninety-third',
            94 =>'Ninety-fourth',
            95 =>'Ninety-fifth',
            96 =>'Ninety-sixth',
            97 =>'Ninety-seventh',
            98 =>'Ninety-eighth',
            99 =>'Ninety-ninth',
            100 =>'One Hundredth',
            101 =>'One Hundred First',
            102 =>'One Hundred Second',
            103 =>'One Hundred Third',
            104 =>'One Hundred Fourth',
            105 =>'One Hundred Fifth',
            106 =>'One Hundred Sixth',
            107 =>'One Hundred Seventh',
            108 =>'One Hundred Eighth',
            109 =>'One Hundred Ninth',
            110 =>'One Hundred Tenth',
            111 =>'One Hundred Eleventh',
            112 =>'One Hundred Twelfth',
            113 =>'One Hundred Thirteenth',
            114 =>'One Hundred Fourteenth',
            115 =>'One Hundred Fifteenth',
            116 =>'One Hundred Sixteenth',
            117 =>'One Hundred Seventeenth',
            118 =>'One Hundred Eighteenth',
            119 =>'One Hundred Nineteenth',
            120 =>'One Hundred Twentieth',
        ];

        return isset($numbers[$number]) ? $numbers[$number] : $number;
    }

    public function emiPayment($hashID){
        if (Auth::user()) {
            $hashids = new Hashids('Creditfair by CS', 20);
            $id = $hashids->decode($hashID);
            $id = $id[0];
            $data = $this->getPaymentData($id);
//        return $data;
            return view('front.application.pay_emi', $data);
        }else {
            return redirect()->intended('application/login');
        }
    }

    public function getPaymentDataV1($id){
        $data = (new AccountingController())->getPayments(new Request(['raw'=>true]), $id, '');
        $data = $data['payments'][0];

        $response = [];
        $totalBounceCharge = 0;
        $totalDelayPenalty = 0;
        $totalChargesWaived = 0;
        $emi_amount = 0;
        $totalDelayDays = 0;
        $pendingAmount = 0;
        $_emi_date = '';
        $reserved = 0;
        foreach ($data['payment'] as $emi_date=>$item){
            if(strtotime($emi_date) < Carbon::now()->endOfMonth()->timestamp) {

                $bounce_charges = 0;
                $delay_penalty = 0;
                $charges_waived = 0;

                if($item['pending_amount'] > 0){
                    $bounce_charges = $item['bounce_charges'];
                    $delay_penalty = $item['delay_penalty'];
                    $charges_waived = $item['charges_waived'];
                }

                $totalBounceCharge += $bounce_charges;
                $totalDelayPenalty += $delay_penalty;
                $totalChargesWaived += $charges_waived;
                $totalDelayDays += $item['delay_days'];
                $pendingAmount += $item['pending_amount'];
                $_emi_date = $emi_date;
                $emi_amount = $item['emi_amount'];

                if($item['pending_amount'] > $emi_amount + $item['bounce_charges'] + $item['delay_penalty']){
                    $reserved += ($item['pending_amount'] - $emi_amount + $item['bounce_charges'] + $item['delay_penalty']);
                }

                $response[$emi_date] = [
                    'bounce_charges' => $bounce_charges,
                    'delay_penalty' => $delay_penalty,
                    'delay_days' => $item['delay_days'],
                    'charges_waived' => $charges_waived,
                    'previous_pending_amount' => $item['pending_amount']
                ];
            }
        }

        return [
            'id' => $id,
            'amount_paid' => 0,
            'emi_amount' => $emi_amount,
            'pending_amount' => $pendingAmount,
            'totalBounceCharge' => $totalBounceCharge,
            'totalDelayPenalty' => $totalDelayPenalty,
            'totalChargesWaived' => $totalChargesWaived,
            'previous_pending_amount' => $reserved,
            'total_pending_til_date' => $pendingAmount,
            'totalDelayDays' => $totalDelayDays,
            'max_amount' => $data['max_payable'],
            'emi_date' => $_emi_date,
            'data' => $response
        ];
    }

    public function getPaymentData($id){
        $emiPayment = new LoanManagement();
        //$emiPayment = new PaymentEmi();

        $payments = $emiPayment->getPaymentDueHistory($id);
        $preData = $payments[$id];
        $payments = $preData['payment'];
        $data = [];
        $amount_paid = 0;
        $pendingAmount = 0;
        $totalBounceCharge = 0;
        $totalDelayPenalty = 0;
        $totalChargesWaived = 0;
        $emi_amount = 0;
        $totalDelayDays = 0;
        $previous_pending_amount = 0;
        $max_amount = 0;
        $_emi_date = '';
        foreach ($payments as $payment){

            $current_amount_paid = 0;
            $max_amount += $payment['emi_amount'];
            if (isset($payment['payment_history']) && isset($payment['payment_history']->transaction)){
                foreach ($payment['payment_history']->transaction as $tranaction){
                    if($tranaction->payment_for == 'EMI') {
                        $amount_paid += $tranaction->amount;
                        $current_amount_paid += $tranaction->amount;
                    }
                }
            }

            if(strtotime($payment->emi_date) < Carbon::now()->endOfMonth()->timestamp) {

                $reservedAmount = $current_amount_paid;
                $reservedAmount = $reservedAmount - $payment['emi_amount'];
                $emi_amount = $payment['emi_amount'];
                $bounce_charge = $payment['bounce_charges'];
                $delay_penalty = $payment['delay_penalty'];
                if($reservedAmount > 0) {
                    $bounce_charge = $payment['bounce_charges'] - $reservedAmount;
                }
                $reservedAmount = $reservedAmount - $payment['bounce_charges'];
                if($reservedAmount > 0) {
                    $delay_penalty = $payment['delay_penalty'] - $reservedAmount;
                }else{
                    $reservedAmount = $reservedAmount + $payment['bounce_charges'];
                }

                $pendingAmount += $payment['pending_amount'];
                $totalBounceCharge += $bounce_charge;
                $totalDelayPenalty += $delay_penalty;
                $totalChargesWaived += $payment['charges_waived'];
                $previous_pending_amount += -$reservedAmount;
                $totalDelayDays += $payment['delay_days'];
                $_emi_date = $payment->emi_date;
                $data[$payment->emi_date] = [
                    'bounce_charges' => $bounce_charge,
                    'delay_penalty' => $delay_penalty,
                    'delay_days' => $payment['delay_days'],
                    'charges_waived' => $payment['charges_waived'],
                    'previous_pending_amount' => - $reservedAmount
                ];
            }
        }

        return [
            'id' => $id,
            'amount_paid' => $amount_paid,
            'emi_amount' => $emi_amount,
            'pending_amount' => $pendingAmount,
            'totalBounceCharge' => $totalBounceCharge,
            'totalDelayPenalty' => $totalDelayPenalty,
            'totalChargesWaived' => $totalChargesWaived,
            'previous_pending_amount' => $previous_pending_amount - $emi_amount,
            'total_pending_til_date' => $pendingAmount,
            'totalDelayDays' => $totalDelayDays,
            'max_amount' => $preData['max_payable'],
            'emi_date' => $_emi_date,
            'data' => $data
        ];
    }

    public function paytmsetup($id, Request $request){
        $payment_for = '';
        $amount = $request->has('data') ? $request->get('data') : 0;
        $hashids = new Hashids('Creditfair by CS', 20);
        $hashID =  $hashids->decode($id);
        if($hashID && isset($hashID[0])){
            $application_id = $hashID[0];
        }else{
            $datasucess = array("application_ids" => 1,"failure"=>"");
            return view('front.payment-failure', $datasucess);
        }

        $consumber_data = ConsumerApplication::with('proFormaInvoice','application_element')->where('id',$application_id)->first();
        $data = array();
        $data['CUST_ID'] = $consumber_data->proFormaInvoice->loan_application_no;
        $foreclosure_date = "";

        if($amount != "" ){
            $amount_hash = wall_decrypt(base64_decode($amount));
            //if(strpos($amount_hash, '|') !== false){
                $amount_hash = explode('|',$amount_hash);
            //}
            $data['TXN_AMOUNT'] = isset($amount_hash[0]) ? $amount_hash[0] : "NA";
            $foreclosure_date = isset($amount_hash[1]) ? $amount_hash[1] : "";
            $payment_for = isset($amount_hash[2]) ? $amount_hash[2] : "";

            if($data['TXN_AMOUNT'] == "NA"){
                $datasucess = array("application_ids" => 1,"failure"=>"");
                return view('front.payment-failure', $datasucess);
            }
        }else {
            //$due = $this->getPayment  Data($application_id);
            $data['TXN_AMOUNT'] = ($consumber_data->application_element && isset($consumber_data->application_element->amount_over_due)) ? $consumber_data->application_element->amount_over_due : 0;
            if (!$data['TXN_AMOUNT']){
                $emiPayment = EmiPayment::where('application_id', $application_id)->whereNotIn('payment_status', ['success'])->first(['emi_amount']);
                $data['TXN_AMOUNT'] = $emiPayment->emi_amount ?? 0;
            }
        }
        if($data['TXN_AMOUNT'] < 1) {
            $datasucess = array("application_ids" => $application_id, 'amount' => $data['TXN_AMOUNT'], 'application_id' => "");
            return view('front.payment-nodue', $datasucess);
        }
        $data['MSISDN'] = $consumber_data->mobile_number;
        $data['EMAIL'] = $consumber_data->email;
        $data['MERC_UNQ_REF'] = $consumber_data->proFormaInvoice->loan_application_no."_".$consumber_data->email."_".$consumber_data->mobile_number;
        if ($request->has('post_approval')) {
            $data['MERC_UNQ_REF'] = $data['MERC_UNQ_REF']."_postApproval";
        }
        $onlinepayment = new OnlinePayment();
        // $onlinepayment = OnlinePayment::where(['application_id' => $application_id, 'purpose' => $payment_for])->first();
        $onlinepayment->application_id = $application_id;
        if($payment_for == 'processing_fee' || $payment_for == 'advance_amount' || $payment_for == 'insurance_fee' || $payment_for == 'emi_and_processing_fee' || $payment_for == 'legal_charges' || $payment_for == "total_fee") {
            $onlinepayment->purpose = $payment_for;
        }else {
            $onlinepayment->purpose = "EMI";
        }
        $onlinepayment->amount = $data['TXN_AMOUNT'];
        $onlinepayment->status = "Pending";
        $onlinepayment->foreclosure_date = $foreclosure_date;
        $onlinepayment->save();
        $data['ORDER_ID'] = $consumber_data->proFormaInvoice->loan_application_no."_".$onlinepayment->id."_".time();

        $data['ORDER_ID'] = substr($data['ORDER_ID'], 0, 25);

        return view('front.paytm',$data);
    }

    public function payment_response(){
        require_once((_env('PAYTM_LIBRARY', '')).'config_paytm.php');
        require_once((_env('PAYTM_LIBRARY', '')).'encdec_paytm.php');
        $paytmParams = $_POST;

        (new Slack(new Request(['title' => 'Paytm response_', 'fields' => ['res' => json_encode($paytmParams)], 'group' => Slack::$STAGE_TESTING])))->send();

        $mongo = new MongoMiddleware();
        $mongo->toMongo(new Request(), new Response(['data' => $paytmParams, 'error' => '']));

        $time = time();

        $merchantKey = PAYTM_MERCHANT_KEY;
        $paytmChecksum = isset($_POST["CHECKSUMHASH"]) ? $_POST["CHECKSUMHASH"] : "";
        $isValidChecksum = verifychecksum_e($paytmParams, $merchantKey, $paytmChecksum);
        if (1 == _env("APP_CONNECTION")) {
            $fln = 'partner/paytm/paytm__call_backresponse_'.$time.'.json';
            ConsumerDocument::uploadToS3TempOnly($fln, json_encode(['response' =>$_POST]));
        }

        if($isValidChecksum == "TRUE" && $paytmParams['STATUS'] == "TXN_SUCCESS") {
            $order_data = explode("_",$paytmParams['ORDERID']);
            $application = ProFormaInvoice::where('loan_application_no', $order_data['0'])->first(['application_id']);
            $applicaion_id = $application->application_id;
            $payment_id = $order_data['1'];
            $merchantKey = PAYTM_MERCHANT_KEY;
            $paytmParams["MID"] = PAYTM_MERCHANT_MID;
            $paytmParams["ORDERID"] = $paytmParams['ORDERID'];
            $paytmChecksum = getChecksumFromArray($paytmParams, $merchantKey);
            $paytmParams['CHECKSUMHASH'] = urlencode($paytmChecksum);
            $postData = "JsonData=".json_encode($paytmParams, JSON_UNESCAPED_SLASHES);
            $connection = curl_init(); // initiate curl
            // $transactionURL = "https://securegw.paytm.in/order/status"; // for production
            $transactionURL = (_env('PAYTM_TRANC_URL', ''));
            curl_setopt($connection, CURLOPT_SSL_VERIFYHOST, 0);
            curl_setopt($connection, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($connection, CURLOPT_URL, $transactionURL);
            curl_setopt($connection, CURLOPT_POST, true);
            curl_setopt($connection, CURLOPT_POSTFIELDS, $postData);
            curl_setopt($connection, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($connection, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
            $responseReader = curl_exec($connection);
            if (1 == _env("APP_CONNECTION")) {
                $fln = 'partner/paytm/paytm_response_'.$time.'.json';
                ConsumerDocument::uploadToS3TempOnly($fln, json_encode(['response' =>$responseReader, 'requests' => $postData]));
            }

            $responseData = json_decode($responseReader, true);
            if($responseData && isset($responseData['STATUS']) && $responseData['STATUS'] == "TXN_SUCCESS"){
                $payment = OnlinePayment::find($payment_id);
                if($payment->status == "TXN_SUCCESS"){
                    $datasucess = array("application_ids" => $applicaion_id,'amount'=>$responseData['TXNAMOUNT'],'application_id'=>$applicaion_id);
                    $applicationData = ConsumerApplication::with('bank_details')->where('id', $applicaion_id)->first();
                    $mandate = Mandate::where('consumer_application_id', $applicaion_id)->whereIn('status',['active','submitted'])->first(['id']);
                    if(!isset($mandate->id) && isset($applicationData->bank_details->bank_name)){
                        $bank_validation = json_decode($applicationData->bank_details->karza_response);
                        if($bank_validation && $applicationData->bank_details->karza_response && $applicationData->bank_details->karza_response != 'false' && isset($bank_validation->result) && $bank_validation->result->bankResponse == 'Transaction Successful') {
                            $hashids = new Hashids('Creditfair by CS', 20);
                            $isFullAmount_hashed_id = $hashids->encode(2);

                            $application_hashed_id = $hashids->encode($applicaion_id);

                            $url = asset("enachrequest/id/" . $application_hashed_id."/".$isFullAmount_hashed_id);

                            $datasucess['nach_url'] = $url;
                        }
                    }
                    // $datasucess['fees'] = $this->getFeesData($applicaion_id);
                    if(isset($paytmParams['MERC_UNQ_REF']) && isset(explode("_", $paytmParams['MERC_UNQ_REF'])[3]) && 
                    explode("_", $paytmParams['MERC_UNQ_REF'])[3] == 'postApproval') {
                        $hashed_id = (new Hashids('Creditfair by CS', 20))->encode($applicaion_id);
                        return redirect()->to('esign/' . $hashed_id . '?type=1&payment=success');
                    }

                    return view('front.payment-congrats', $datasucess);
                }
//                $payment->status = $responseData['STATUS'];
//                $payment->response = json_encode($paytmParams);
                $payment->save();
                $payment_emi = new LoanManagement();

                $payment_type = (isset($payment->purpose) && !empty($payment->purpose)) ? $payment->purpose : 'EMI';
                if($payment_type == 'emi_and_processing_fee'){
                    $payment_type = 'EMI';
                    $applicationEMICalculation = ApplicationEMICalculation::where('application_id', $applicaion_id)->first(['emi', 'processing_fee']);
                    if (isset($applicationEMICalculation->emi) && $responseData['TXNAMOUNT'] > $applicationEMICalculation->emi && $applicationEMICalculation->processing_fee){
                        $isProcessing = $responseData['TXNAMOUNT'] - $applicationEMICalculation->emi;
                        if($isProcessing > 0 && $applicationEMICalculation->processing_fee == $isProcessing){
                            $responseData['TXNAMOUNT'] = $applicationEMICalculation->emi;
                            $this->processProcessingFee($applicaion_id, $responseData, $payment, $applicationEMICalculation->processing_fee);
                        }
                    }
                }

                $data['amount'] = $responseData['TXNAMOUNT'];
                $data['payment_date'] = date('Y-m-d');
                $data['mode'] = "Paytm";
                $data['paid_by'] = "";
                $data['collected_by'] = "";
                $data['bank_id'] =  (new ConsumerApplicationController())->getTransactionBank($applicaion_id);
                $data['wallet_name'] = "";
                $data['application_id'] = $applicaion_id;
                $data['trasanction_id'] = $responseData['TXNID'];
                $data['online_payment_id'] = $payment->id;
                $data['fore_closure_date'] = isset($payment->foreclosure_date) ? $payment->foreclosure_date : '';
                $data['trasanction_acknowledgement'] = "";
                $data['payment_type'] = $payment_type;
//                $payment_emi->paymentReconcile($data);

                if(isset($payment->purpose) && $payment->purpose == 'emi_and_processing_fee' && $isProcessing){
                    $responseData['TXNAMOUNT'] += $isProcessing;
                }

                $datasucess = array("application_ids" => $applicaion_id,'amount'=>$responseData['TXNAMOUNT'],'application_id'=>$order_data[0]);
                $applicationData = ConsumerApplication::with('bank_details')->where('id', $applicaion_id)->first();
                $mandate = Mandate::where('consumer_application_id', $applicaion_id)->whereIn('status',['active','submitted'])->first(['id']);
                if(!isset($mandate->id) && isset($applicationData->bank_details->bank_name)){
                    $bank_validation = json_decode($applicationData->bank_details->karza_response);
                    if($bank_validation && $applicationData->bank_details->karza_response && $applicationData->bank_details->karza_response != 'false' && isset($bank_validation->result) && $bank_validation->result->bankResponse == 'Transaction Successful') {
                        $hashids = new Hashids('Creditfair by CS', 20);
                        $isFullAmount_hashed_id = $hashids->encode(2);

                        $application_hashed_id = $hashids->encode($applicaion_id);

                        $url = asset("enachrequest/id/" . $application_hashed_id."/".$isFullAmount_hashed_id);

                        $datasucess['nach_url'] = $url;
                    }
                }
                // $datasucess['fees'] = $this->getFeesData($applicaion_id);
                if(isset($paytmParams['MERC_UNQ_REF']) && isset(explode("_", $paytmParams['MERC_UNQ_REF'])[3]) && 
                    explode("_", $paytmParams['MERC_UNQ_REF'])[3] == 'postApproval') {
                        $hashed_id = (new Hashids('Creditfair by CS', 20))->encode($applicaion_id);
                        return redirect()->to('esign/' . $hashed_id . '?type=1&payment=success');
                    }
                return view('front.payment-congrats', $datasucess);
            }
        }
        if(isset($paytmParams['MERC_UNQ_REF']) && isset(explode("_", $paytmParams['MERC_UNQ_REF'])[3]) && 
            explode("_", $paytmParams['MERC_UNQ_REF'])[3] == 'postApproval' && isset($paytmParams['ORDERID'])) {
                $order_data = explode("_",$paytmParams['ORDERID']);
                $application = ProFormaInvoice::where('loan_application_no', $order_data['0'])->first(['application_id']);
                $applicaion_id = $application->application_id;
                $hashed_id = (new Hashids('Creditfair by CS', 20))->encode($applicaion_id);
                return redirect()->to('esign/' . $hashed_id . '?type=1&payment=fail');
            }
        $datasucess = array("application_ids" => 1,"failure"=>"");
        return view('front.payment-failure', $datasucess);
    }

    public function razorpay_payment_response(){
        $razorpayPaymentlinkId = $_GET['razorpay_payment_link_id'];
        $razorpayPaymentId = $_GET['razorpay_payment_id'];
        $razorpayPaymentLinkReferenceId = $_GET['razorpay_payment_link_reference_id'];
        $razorpayPaymentLinkStatus = $_GET['razorpay_payment_link_status'];
        $razorpayPaymentLinkSignature = $_GET['razorpay_signature'];
        $data = OnlinePayment::where('payment_id', $razorpayPaymentlinkId)->first(['application_id','amount']);
        $lender = ConsumerApplication::where('id',$data->application_id)->first(['lender_id']);
        $lender_id = $lender->lender_id;
        $application_id = $data->application_id;
        if ($lender_id == 2) {
            $api = new Api(_env('KMRAZORPAYKEY', ''), _env('KMRAZORPAYSECRET', ''));
        }elseif($lender_id == AvanseServices::$lender_id){
            //return $this->initAvProcess($data['id']);
            $api = new Api(_env('AVANSERAZORPAYKEY', ''), _env('AVANSERAZORPAYSECRET', ''));
        }elseif($lender_id == Services::$lender_id){
            $api = new Api(_env('ABFLRAZORPAYKEY', ''), _env('ABFLRAZORPAYSECRET', ''));
        }elseif($lender_id == LendBox::$lender_id || $lender_id == LendBoxLSP::$lender_id){
            $api = new Api(_env('LENDBOX_RAZORPAYKEY', ''), _env('LENDBOX_RAZORPAYSECRET', ''));
        }elseif ($lender_id == KMGP2P::$lender_id ) {
            $api = new Api(_env('KMGP2PRAZORPAYKEY', ''), _env('KMGP2PRAZORPAYSECRET', ''));
        }elseif ($lender_id == JMServices::$lender_id ) {
            $api = new Api(_env('JMFLRAZORPAYKEY', ''), _env('JMFLRAZORPAYSECRET', ''));
        }elseif ($lender_id == Vivriti::$lender_id ) {
            $api = new Api(_env('VIVRITIRAZORPAYKEY', ''), _env('VIVRITIRAZORPAYSECRET', ''));
        }else {
            $api = new Api(_env('PRIDERAZORPAYKEY', ''), _env('PRIDERAZORPAYSECRET', ''));
        }
        try {
            $api->utility->verifyPaymentSignature(array('razorpay_payment_link_id' => $razorpayPaymentlinkId, 'razorpay_payment_id' => $razorpayPaymentId, 'razorpay_payment_link_reference_id' => $razorpayPaymentLinkReferenceId, 'razorpay_payment_link_status' => $razorpayPaymentLinkStatus, 'razorpay_signature' => $razorpayPaymentLinkSignature));
            $paymentSignatureVerification = true;
            (new Slack(new Request(['title' => 'verifyPaymentSignature - Success', 'fields' => ['Message' => 'Success', 'id' => $application_id], 'group' => Slack::$STAGE_TESTING])))->send();
        }catch (\Exception $e){

        }
        $p = $api->payment->fetch($razorpayPaymentId);
        if($p->status == "captured"){
            $paymentSignatureVerification = true;
            // (new ConsumerApplicationController())->vendorWebhook($application_id, ['type' => 'RazorPay-Webhook','status' => 'Success']);
        }else{
            $paymentSignatureVerification = false;
        }
        $datasucess = array();
        if($paymentSignatureVerification == true){
            $applicationData = ConsumerApplication::with('bank_details')->where('id', $application_id)->first();
            $mandate = Mandate::where('consumer_application_id', $application_id)->whereIn('status',['active','submitted'])->first(['id']);
            if(!isset($mandate->id) && isset($applicationData->bank_details->bank_name)){
                $bank_validation = json_decode($applicationData->bank_details->karza_response);
                if($bank_validation && $applicationData->bank_details->karza_response && $applicationData->bank_details->karza_response != 'false' && isset($bank_validation->result) && $bank_validation->result->bankResponse == 'Transaction Successful') {
                    $hashids = new Hashids('Creditfair by CS', 20);
                    $isFullAmount_hashed_id = $hashids->encode(2);

                    $application_hashed_id = $hashids->encode($application_id);

                    $url = asset("enachrequest/id/" . $application_hashed_id."/".$isFullAmount_hashed_id);

                    $datasucess['nach_url'] = $url;
                }
            }
            $datasucess['application_id'] = $data->application_id;
            $datasucess['amount'] = $data->amount;
            $datasucess['fees'] = $this->getFeesData($data->application_id);
            return view('front.razorpay-payment-congrats', $datasucess);
        }else{
            $datasucess = array("application_ids" => $application_id,"failure"=>"");
            return view('front.payment-failure', $datasucess);
        }
    }

    public function campaign(){
        return view('campaign');
    }


    public function processProcessingFee($applicaion_id, $responseData, $payment, $processingFeeAmount){

        $data['amount'] = $processingFeeAmount;
        $data['payment_date'] = date('Y-m-d');
        $data['mode'] = "Paytm";
        $data['paid_by'] = "";
        $data['collected_by'] = "";
        $data['bank_id'] =  (new ConsumerApplicationController())->getTransactionBank($applicaion_id);
        $data['wallet_name'] = "";
        $data['application_id'] = $applicaion_id;
        $data['trasanction_id'] = $responseData['TXNID'];
        $data['online_payment_id'] = $payment->id;
        $data['fore_closure_date'] = isset($payment->foreclosure_date) ? $payment->foreclosure_date : '';
        $data['trasanction_acknowledgement'] = "";
        $data['payment_type'] = 'processing_fee';

        $payload[] = [
            'payload' => json_encode($data),
            'from' => 'paytm_processing_fee_process',
            'application_id' => $applicaion_id,
            'available_at' => Carbon::now()->toDateTimeString(),
            'created_at' => Carbon::now()->toDateTimeString()
        ];

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



//    New Website Pages

    public function getAboutUs()
    {
        $data = array();
        $data['is_home'] = true;
        $data['seo_data'] = $this->getSEOData();

        $data['teams'] = [
            // ['name' => 'APURVA SHAH', 'image' => 'Apurva Shah.png', 'gif' => '', 'designation' => 'VP - Sales & Operations','linkedin' => 'https://www.linkedin.com/in/adshah2012/'],
//            ['name' => 'Darshan Mehta', 'image' => 'darshan.jpg', 'gif' => 'darshan.gif', 'designation' => 'Business Development Manager'],
//            ['name' => 'Dinesh Kumar Rana', 'image' => 'dinesh.jpg', 'gif' => 'dinesh.gif', 'designation' => 'Quality Analyst'],
            //['name' => 'Gaurav Kumar', 'image' => 'gaurav.jpeg', 'gif' => 'gaurav.gif', 'designation' => 'CTO'],
            // ['name' => 'PAWAN PANDEY', 'image' => 'Pawan.png', 'gif' => '', 'designation' => 'Senior Manager - Operations','linkedin' =>'https://www.linkedin.com/in/pawan-pandey-46531457/'],
//            ['name' => 'Harsha Shivalya', 'image' => 'Harsha.jpg', 'gif' => 'harshagif.gif', 'designation' => 'HR Manager'],
            ['name' => 'PIYUSH BANG', 'image' => 'Piyush Bang.png', 'gif' => '', 'designation' => 'Chief Manager - Business Development','linkedin' =>'https://www.linkedin.com/in/piyush-bang-b45956a1/'],
//            ['name' => 'Kailash Patere', 'image' => 'Kailash.jpeg', 'gif' => 'kailash.gif', 'designation' => 'Credit Executive'],
            ['name' => 'IMRAN KHAN', 'image' => 'Imran Khan.png', 'gif' => '', 'designation' => 'Head of Collections','linkedin' =>'https://www.linkedin.com/in/imran-khan-78009864/'],
            //['name' => 'MOHAMMED IRSHAD', 'image' => 'Irshad.jpg', 'gif' => '', 'designation' => 'Head of Engineering'],
//            ['name' => 'Mohammed Zafar Ustad', 'image' => 'zafar.jpg', 'gif' => 'zafar.gif', 'designation' => 'Frontend Developer'],
//            ['name' => 'Omprakash Sharma', 'image' => 'om.jpg', 'gif' => 'om.gif', 'designation' => 'Operations Executive'],
            ['name' => 'SUNIL KHORWAL', 'image' => 'Sunil Khorwal.png', 'gif' => '', 'designation' => 'Associate Vice President - Technology','linkedin' =>'https://www.linkedin.com/in/sunil-khorwal/'],
            //['name' => 'SHRENIK SHAH', 'image' => 'Shrenik.png', 'gif' => '', 'designation' => 'Vice President - Credit & Lending Partnerships','linkedin' =>'https://in.linkedin.com/in/ca-shrenik-d-shah-6575038b'],
            ['name' => 'SHRADDHA MANDLIK', 'image' => 'Shraddha Mahadik.png', 'gif' => '', 'designation' => 'Senior Manager - Credit','linkedin' =>'https://www.linkedin.com/in/shraddha-mandlik-724a60164/'],
//            ['name' => 'Prerna Gupta', 'image' => 'prerna.jpg', 'gif' => 'mahima.gif', 'designation' => 'Product Lead'],
            ['name' => 'Mahalaxmi Srinivasan', 'image' => 'Mahalaxmi.png', 'gif' => '', 'designation' => 'Manager - Disbursement'],
            ['name' => 'SANTOSH JHA', 'image' => 'Santosh Jha.png', 'gif' => '', 'designation' => 'Head - Finance & Accounting'],
//            ['name' => 'Saket Chaudhari', 'image' => 'saket.jpg', 'gif' => 'saket.gif', 'designation' => 'City Head Pune'],
            //['name' => 'MEHUL MAHANT', 'image' => 'Mehul.png', 'gif' => '', 'designation' => 'Head - Human Resources','linkedin' =>'https://www.linkedin.com/in/mehul-mahant-99948228/'],
            //['name' => 'APEKSHA BHANDARI', 'image' => 'Apeksha.png', 'gif' => '', 'designation' => 'Associate Vice President - Product & Marketing','linkedin' =>'https://www.linkedin.com/in/apekshabhandari/'],
            ['name' => 'Disha Doshi', 'image' => 'Disha Doshi.png', 'gif' => '', 'designation' => 'Senior Product Manager','linkedin' =>'https://www.linkedin.com/in/disha-doshi-linked-in/'],
            ['name' => 'Rishabh Aditya', 'image' => 'Rishabh Aditya.png', 'gif' => '', 'designation' => 'Chief Manager - Sales & Ops','linkedin' =>'https://in.linkedin.com/in/rishabh-aditya007'],
            //['name' => 'Nisha Mehta', 'image' => 'Nisha Photo EL.jpg', 'gif' => '', 'designation' => 'HR Lead','linkedin' =>'https://www.linkedin.com/in/nisha-mehta-233b1271/'],
            // ['name' => 'Asish Singh', 'image' => 'Asish.png', 'gif' => '', 'designation' => 'Senior Manager - Operations','linkedin' =>' https://in.linkedin.com/in/ashish-singh-123714103?trk=public_post_feed-actor-name'],
            // ['name' => 'Rajendra Amballa', 'image' => 'rajendra_amballa.png', 'gif' => '', 'designation' => 'Senior Manager Business Development','linkedin' =>'https://www.linkedin.com/in/rajendra-amballa-86673a29/'],
            ['name' => 'Neha Pathak', 'image' => 'Neha Pathak.png', 'gif' => '', 'designation' => 'Manager - Lending Partnership','linkedin' =>'https://www.linkedin.com/in/neha-pathak-7550a1163/'],
            // ['name' => 'MEET GOPANI', 'image' => 'Meet.png', 'gif' => '', 'designation' => 'Product Manager Analytics','linkedin' =>'https://www.linkedin.com/in/meet-gopani-5b2120139/'],
            ['name' => 'Ravi Mehta', 'image' => 'Ravi Mehta.png', 'gif' => '', 'designation' => 'Senior Manager ','linkedin' =>''],
            // ['name' => 'Rahul Vaidya', 'image' => 'rahul_vaidya.png', 'gif' => '', 'designation' => 'Director','linkedin' =>'https://www.linkedin.com/in/rahul-vaidya-182155a/'],
            // ['name' => 'Shraddha Mandlik', 'image' => 'shraddha_compressed.jpg', 'gif' => 'shraddha.gif', 'designation' => 'Senior Credit Manager'],
            // // ['name' => 'Snneha Lukaa', 'image' => 'snneha.jpeg', 'gif' => 'ashwini.gif', 'designation' => 'Marketing Manager'],
            // ['name' => 'Sumedh Bhalerao', 'image' => 'sumedh.jpg', 'gif' => 'sumedh.gif', 'designation' => 'Business Development Manager'],
            // ['name' => 'Sunil Khorwal', 'image' => 'sunil.jpg', 'gif' => 'sunil.gif', 'designation' => 'Lead Developer'],
            // ['name' => 'Suraj Jagtap', 'image' => 'suraj.jpg', 'gif' => 'suraj.gif', 'designation' => 'Business Development Manager'],
            // ['name' => 'Surbhi Sawant', 'image' => 'SURBHI SAWANT.jpeg', 'gif' => 'surbhi.gif', 'designation' => 'Accounts Executive'],
            // ['name' => 'Yuvraj Khorwal', 'image' => 'yuvraj.jpg', 'gif' => 'yuvraj.gif', 'designation' => 'Backend Developer'],
//            ['name' => '', 'image' => '', 'gif' => '', 'designation' => ''],
        ];
        // return view('about_us_page_v2', $data);
        return view('about_us_page_v2', $data);

    }

    public function getMerchantPage()
    {
        $data = array();
        $data['is_home'] = true;
        $data['seo_data'] = $this->getSEOData();
        return view('front.pages.merchant_page', $data);
    }

    public function getCustomerPage()
    {
        $data = array();
        $data['is_home'] = true;
        $data['seo_data'] = $this->getSEOData();
        return view('front.pages.customer_page', $data);
    }

    public function getDeleteInfoPage()
    {
        $data = array();
        $data['is_home'] = true;
//        $seo_data = WebSEO::where('url','customer')->first(['title','meta']);
//        if(isset($seo_data)&&!empty($seo_data)){
//            $data['title'] = $seo_data->title;
//            $data['meta'] = $seo_data->meta ? $seo_data->meta : '';
//        }
        return view('front.pages.delete_user_info', $data);
    }

    public function getPersonalLoans()
    {
        $data = array();
        $data['is_home'] = true;
        $data['title'] = 'Credit Fair | Personal Loan';
        return view('front.pages.sectors.personal', $data);
    }

    public function getEducationalLoans()
    {
        $data = array();
        $data['is_home'] = true;
        $data['title'] = 'Credit Fair | Education Loan';
        return view('front.pages.sectors.education', $data);
    }

    public function getHomeDecor($category)
    {
        $data['page'] = Config::get('homeDecor')[$category];
        $data['title'] = 'Credit Fair | Home Decor';
        return view('front.pages.sectors.home_decor', $data);
    }

    public function getHealthCare($category)
    {
        $data['page'] = Config::get('healthCare')[$category];
        $data['title'] = 'Credit Fair | HealthCare';
        return view('front.pages.sectors.health_care', $data);
    }

    public function getEVehicles()
    {
        $data = array();
        $data['is_home'] = true;
        $data['title'] = 'Credit Fair | E-Vehicles';
        return view('front.pages.sectors.e-vehicles', $data);
    }

    public function getCareers()
    {
        $data = array();
        $data['is_home'] = true;
        $data['seo_data'] = $this->getSEOData();
        $data['careers'] = Careers::with('user')->where('status','active')->get();
        // dd($data['careers']);
        $data['positions'] = Departments::with('user','career')->get();
        return view('front.pages.careers', $data);
    }

    public function getContact()
    {
        $data = array();
        $data['is_home'] = true;
        $data['seo_data'] = $this->getSEOData();
        return view('front.pages.contact', $data);
    }

    public function getLogin()
    {
        if (\Auth::check()) {
            return redirect()->intended('application/history');
        } else {
            $data = array();
            return view('front.login', $data);
        }
    }

    public function getInvalidPage()
    {
        return view('errors.404');
    }

    public function getFaqPage()
    {
        $data['seo_data'] = $this->getSEOData();
        return view('front.pages.faq_page',$data);
    }

    public function getMaintenancePage()
    {
        return view('front.pages.maintenance');
    }

    public function getOldApplication()
    {
        $merchant_id = $this->getMerchantHash();
        $merchant_slug = (Input::has('txn')) ? (Input::get('txn')): " " ;
        if($merchant_id > 0 || $merchant_slug != ""){
            $merchant = Merchant::with('offer')->where('id',$merchant_id)->orWhere('slug',$merchant_slug)->first();
            if(isset($merchant->id)) {
                $merchant_id = $merchant->id;
                if (isset($merchant->category_id)) {
                    $data['merchant_details'] = Merchant::where('status', 'active')->where('id', $merchant_id)->get();
                    $data['selectedMerchantCategoryID'] = $merchant->category_id;
                    $data['selectedMerchantOffers'] = $merchant->offer;
                    $data['selectedMerchant'] = $merchant;
                }
            }
        }
        $data['docs'] = true;
        $data['states'] = $this->state;
        $data['merchant_list'] = Merchant::where('status','active')->get(['merchant_name as name','id']);
        $data['merchant_category'] = MerchantCategory::where('status',1)->get(['name','id']);
        $data['selectedMerchantID'] = $merchant_id;
        $data['selectedMerchantIDCat'] = (isset($data['selectedMerchantCategoryID'])) ? $data['selectedMerchantCategoryID'] : 0;
        $data['inverter_list'] = (new ConsumerApplicationController())->inverterList();
        $data['panel_list'] = (new ConsumerApplicationController())->panelList();
        return view('front.application.application', $data);
//        return view('front.pages.forms.apply_now');
    }

    public function becomePartner(){
        //$hex = unpack("H*", file_get_contents('/home/sunil/Desktop/test.pdf'));
        //return $hex = current($hex);
        //$chars = pack("H*", $hex);
//        $data['isapp'] = isset($_GET['is_app']) ? $_GET['is_app'] : 0;
//        $data['is_home'] = true;
        return view('front.pages.forms.brand_partner');
    }

    public function getTermsConditions()
    {
        $data['seo_data'] = $this->getSEOData();
        return view('front.pages.legal.terms-conditions',$data);
    }

    public function getPrivacyPolicy()
    {
        $data['seo_data'] = $this->getSEOData();
        return view('front.pages.legal.privacy-policy',$data);
    }

    public function getFairPracticePolicy()
    {
        $data['seo_data'] = $this->getSEOData();
        return view('front.pages.legal.fair-practice-policy', $data);
    }

    public function getListOfLSP(){
        $data['seo_data'] = $this->getSEOData();
        return view('front.pages.legal.lsp', $data);
    }

    public function getListOfDLA(){
        $data['seo_data'] = $this->getSEOData();
        return view('front.pages.legal.dla', $data);
    }

    public function getGrievancePolicy(){
        $data['seo_data'] = $this->getSEOData();
        return view('front.pages.legal.grievance-policy', $data);
    }

    public function getCodeOfConduct(){

        return view('front.pages.legal.code-of-conduct');
    }

    public function getOutsourcingPolicy()
    {
        $data['seo_data'] = $this->getSEOData();
        return view('front.pages.legal.outsourcing-policy', $data);
    }

    public function getAffiliatePartnersPolicy(){
        $data['seo_data'] = $this->getSEOData();
        return view('front.pages.legal.affiliate-partners', $data);
    }

    public function getKYCPolicy()
    {
        $data['seo_data'] = $this->getSEOData();
        return view('front.pages.legal.kyc-policy',$data);
    }

    public function verifyEmail($hash_id){

        $hash = new Hashids('Creditfair by CS', 20);
        $id = $hash->decode($hash_id);
        if (isset($id[0]) && is_numeric($id[0])){
            $id = $id[0];
            $user = Customers::where('id', $id)->first(['id','is_verified']);
            if (isset($user->id) && $user->is_verified == 1){
                return view('front.application.email-verification', ['status' => 0]);
            }else{
                Customers::where('id', $id)->update(['is_verified' => 1]);
                return view('front.application.email-verification', ['status' => 1]);
            }
        }

        return view('front.application.email-verification', ['status' => 2]);
    }

    public function verifyOTP(Request $request, $hash_id, $request_id){

        $hash = new Hashids('Creditfair by CS', 20);
        $id = $hash->decode($hash_id);
        if (isset($id[0]) && is_numeric($id[0])){
            $id = $id[0];
            $application = ConsumerApplication::where('id', $id)->whereNull('is_deleted')->with('user')->first(['id','user_id']);
            $user = $application->user;
            if (isset($user->id) && $user->user_verified == 1){
                return view('front.otp-verification', ['status' => 0]);
            }else if ($request->has('otp') && $request->get('otp')){
                $mobile_number = $user->mobile_number;
                if (strlen($user->mobile_number) == 12 && substr($user->mobile_number, 0, 2) == "91") {
                    $mobile_number = substr($user->mobile_number, 2, 10);
                }

                $telecom = new TelecomDetails();
                $response = $telecom->verifyOtp($request->get('request_id'),$request->get('otp'),'',$mobile_number);
                if($response == false){
                    return view('front.otp-verification', ['status' => 2, 'retry' => 1, 'name' => $user->name, 'hash_id' => $hash_id, 'request_id' => $request_id]);
                }else{
                    User::where('id', $user->id)->update(['user_verified' => 1]);
                    return view('front.otp-verification', ['status' => 1, 'name' => $user->name]);
                }
            }

            return view('front.otp-verification', ['status' => 2, 'retry' => 1, 'name' => $user->name, 'hash_id' => $hash_id, 'request_id' => $request_id]);
        }

        abort(404);
    }

    public function getFinbitIntegration($id){
        $finbitConnect = new FinBit(new Request());
        $token = $finbitConnect->token;

        return view('front.finbit-integration', ['token' => $token,'id' => $id]);
    }

    public function getFinbitResponse(Request $request){
        try {
            $id = $request->get('id');
            if (1 === _env('LOG_FINTBIT_RESPONSE')) {
                $myfile = "finbit/".$request->get('id')."_finbit_res.txt";
                $txt = json_encode($request->all());
                Storage::disk('s3')->put($myfile, $txt);
            }

            $data = (array) $request->all();
            $response = $request->get('response');
            $data['bank_name'] = isset($response['bank']) ? $response['bank'] : '';
            $finBit = new FinBit(new Request($data));
            $finBit->response = (object)$response;
            $finBit->getExcel();
            $finBit->getPDF();
            $finBit->getStatementDetails();
            $finBit->getFraudReport();

            $application = ConsumerApplication::with('merchant', 'advisor')->where('id', $id)->first(['id','name','email','merchant_id', 'created_by']);
            if(isset($application->id) && (!isset($response['status']) || (isset($response['status']) && $response['status'] != 'ERROR'))){
                $merchant_name = $application->merchant ? 'Merchant Name - '.$application->merchant->merchant_name : '';
                $advisor_id = isset($application->advisor) && isset($application->advisor->id) ? $application->advisor->id : '';
                (new Slack(new Request(['title' => 'Bank Statement Uploaded by '.$application->name.'| '.$application->id.' '.$merchant_name, 'fields' => ['name' => $application->name, 'email' => $application->email, 'Application ID' => $application->id], 'group' => 'loan_application', 'tagging' => [$advisor_id]])))->send();
            }


            return \response()->json(['status' => 'OK'], 200);
        }catch (\Exception $e){
            (new Slack(new Request(['title' => 'Bank Statement - Finbit Error', 'fields' => ['error' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString(), 'application_id' => $id, 'id_type' => 'application_id'], 'group' => Slack::$STAGE_TESTING])))->send();
            return \response()->json(['status' => 'OK'], 200);
        }
    }

    public function onfidoToken($id, $applicant_type = 'Applicant'){
        $application = ConsumerApplication::where('id', $id)->first();
        $names = $applicant_type === 'Applicant' ? explode(' ',$application->name) : explode(' ',$application->co_applicant_name);
        $firstName = $names[0];
        unset($names[0]);
        $names = implode(' ',$names);

        $building = '';
        $street = '';
        $town = '';
        $postcode = '';
        $addressees = (new ConsumerApplicationController())->getAddressByType($application);
        if($applicant_type === 'Applicant'){
            if($addressees['applicant']['current']['address']){
                $postcode = $addressees['applicant']['current']['pincode'];
                $building = $application->current_address_line_1;
                $street = $application->current_address_landmark;
                $town = $application->current_address_city.' '.$application->current_address_state;
            }else if ($addressees['applicant']['permanent']['address']){
                $postcode = $addressees['applicant']['permanent']['pincode'];
                $building = $application->permanent_address_line_1;
                $street = $application->permanent_address_landmark;
                $town = $application->permanent_address_city.' '.$application->permanent_address_state;
            }
        }else{
            if ($addressees['co_applicant']['current']['address']){
                $postcode = $addressees['co_applicant']['current']['pincode'];
                $building = $application->co_applicant_address_line_1;
                $street = $application->co_applicant_address_landmark;
                $town = $application->co_applicant_address_city.' '.$application->co_applicant_address_state;
            }
        }


        $payload = [
            "first_name" => trim($firstName),
            "last_name" =>  trim($names) ?  trim($names) : 'something',
            "dob" =>  $application->dob,
            "address" =>  [
                "building_number" =>  $building,
                "street" =>  $street,
                "town" =>  $town,
                "postcode" =>  $postcode,
                "country" =>  "IND"
            ]
        ];
        return (new OnfidoIntegration())->createApplicant($id, $payload);
    }

    public function getSitemap(){
        $routeCollection = \Illuminate\Support\Facades\Route::getRoutes();
        $routes = [];
        foreach ($routeCollection as $route){
            $routeView = $route->getAction();
            if(isset($routeView['as']) && strpos($routeView['as'], 'web_') !== false) {
                if($route->uri() == '/'){
                    array_push($routes, $route->uri());
                }else{
                    array_push($routes, '/'.$route->uri());
                }

            }
        }
        $staticPages= StaticPage::where('is_published', 1)->get(['url']);
        foreach ($staticPages as $page){
            array_push($routes, '/page/'.$page->url);
        }
        $siteUrl = URL::to('/');
        $timestamp = gmdate('Y-m-d', time());//Carbon::now()->toDateTimeString();
        $xmlString1 = '';
        foreach ($routes as $route) {
            $xmlString2 = "
        <url>
            <loc>$siteUrl$route</loc>
            <lastmod>$timestamp</lastmod>
            <changefreq>weekly</changefreq>
        </url>";
            $xmlString1 = $xmlString1 . $xmlString2;
        }

        $xmlString = '<?xml version="1.0" encoding="UTF-8"?>
    <urlset>' . $xmlString1 . '
    </urlset>';

        $dom = new \DOMDocument();
        $dom->preserveWhiteSpace = FALSE;
        $dom->loadXML($xmlString);

//Save XML as a file
        $dom->save('sitemap.xml');

        $t= file_get_contents('sitemap.xml');
        return response(file_get_contents('sitemap.xml'), 200, [
            'Content-Type' => 'application/xml'
        ]);
    }

    public function startTracking($tracking_string, Request $request){

        try {


            if ($request->has('redirect') && strpos($request->get('redirect'), 'LEGACY') !== false){
                $stringURL = explode('&', 'redirect='.str_replace('LEGACY', '&', $request->get('redirect')));
                $segments = [];
                foreach ($stringURL as $item) {
                    $itemD = explode('=', $item);
                    $segments[$itemD[0]] = $itemD[1];
                }
                $request = new Request($segments);
            }

            $hashids = new Hashids('Creditfair by CS', 20);
            $tracking_string = $hashids->decode($tracking_string);

            $enc_str = $request->get('enc_str');
            $enc_str = str_replace('@14@','+',$enc_str);

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

                $source = 'UNKNOWN';

                switch ($request->get('source')){
                    case 1:
                        $source = 'MAIL';
                        break;
                    case 2:
                        $source = 'WHATSAPP';
                        break;
                    case 3:
                        $source = 'SMS';
                        break;
                    case 4:
                        $source = 'FCM';
                        break;
                }

                $payload = wall_decrypt($enc_str);
                $payloadDecrypted = json_decode($payload);
                $user_id = isset($payloadDecrypted->id) ? trim($payloadDecrypted->id) : null;
                $user_id = str_replace(' ','',$user_id);
                $CampaignTracking = CampaignTracking::where('campaign_id', $tracking_string[0])->where('user_id', $user_id)->where('source', trim($source))->first();
                if($payload){
                    if(!isset($CampaignTracking->id) && $user_id > 0) {
                        CampaignTracking::insert([
                            'campaign_id' => $tracking_string[0],
                            'payload' => $payload,
                            'impression' => 1,
                            'user_id' => $user_id,
                            'source' => trim($source),
                            'created_at' => Carbon::now()->toDateTimeString()
                        ]);
                    }else{
                        CampaignTracking::where('campaign_id', $tracking_string[0])->where('user_id', $user_id)->where('source', trim($source))->update([
                            'impression' => $CampaignTracking->impression + 1,
                            'updated_at' => Carbon::now()->toDateTimeString()
                        ]);
                    }
                }
            }

            if ($request->has('redirect') && $request->get('redirect') && $request->has('enc_str')) {
                return Redirect::to($request->get('redirect'));
            }

            $storagePath = public_path('/assets/front/img/track_img.png');
            return response()->file($storagePath, ['Content-Type' => 'image/png']);
        }catch (\Exception $e){
            (new Slack(new Request(['title' => 'Error Campaign (Testing)', 'fields' => ['error'=>$e->getMessage(),'line'=>$e->getLine(),'trace'=>$e->getTraceAsString()]])))->send();
            return Redirect::to('/');
        }
    }

    /*public function chat(){
        return view('front.chat');
    }*/

    public function cashfreeWebhook(Request  $request){

        try {
            (new CF_Logs())->webhook($request);

            //(new Slack(new Request(['title' => 'CashFree Webhook Update', 'fields' => ['res' => json_encode($request->all())], 'group' => Slack::$STAGE_TESTING])))->send();
        }catch (\Exception $e){

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

    public function saveHypervergeWebhook(Request $request){
        $hyper = new HypervergeVideo($request);
        $hyper->setHypervergeVideoAttribute($request->all(), 'webhook');
        return \response()->json(['status' => 'OK'], 200);
    }

    public function saveKarzaWebhook(Request $request){
        $hyper = new KarzaVideo($request);
        (new Slack(new Request(['title' => 'Save Karza Webhook', 'fields' => ['res' => json_encode($request->all())], 'group' => Slack::$STAGE_TESTING])))->send();
        $hyper->setKarzaVideoAttribute($request->all(), 'webhook');
        return \response()->json(['status' => 'OK'], 200);
    }

    public function HyperN($key, $seg){
        $client = new \GuzzleHttp\Client();
        $response = $client->request('GET', 'https://vcip-customer.hyperverge.co/'.$key.'/'.$seg);

        return $response->getBody();
    }

    public function HyperV($key, $seg){
        $client = new \GuzzleHttp\Client();
        $response = $client->request('GET', 'https://vcip-prequal.hyperverge.co/'.$key.'/'.$seg);

        return $response->getBody();
    }

    public function CFInternalWebhook(Request $request){
        if($request->has('applicationNo')) {
            (new Slack(new Request(['title' => 'mConnect Webhook - Success', 'fields' => ['payload' => json_encode($request->all())], 'group' => Slack::$STAGE_TESTING])))->send();
        }
        abort(404);
    }

    public function generateDocumentId(Request $request) {
        try {
            if($request->ajax()){
                $inputs = $request->all();
                if(empty($inputs['application_id']) || empty($inputs['partner'])) {
                    return \response()->json(['status' => 'failed','error' => 'Invalid inputs'], 200);
                }
                $type = 'electronic'; // otp
                if(isset($inputs['is_aadhaar']) && $inputs['is_aadhaar'] == 1) {
                    $type = 'aadhaar';
                }
                $app = ConsumerApplication::where('id', $inputs['application_id'])->first();
                if ($app instanceof ConsumerApplication) {
                    $data = LoanAgreementVendor::sendLoanAgreementToVendor($inputs['partner'], $app, $type);
                    if(!empty($data['doc_id'])) {
                        return \response()->json(['status' => 'OK', 'data' => $data], 200);
                    } else {
                        return \response()->json(['status' => 'failed','error' => 'Some error occured'], 200);
                    }
                } else {
                    return \response()->json(['status' => 'failed','error' => 'Invalid loan id'], 200);
                }
            }
            return \response()->json(['status' => 'failed','error' => 'Some error occured'], 200);

        } catch (\Exception $e){
            //return \response()->json(['status' => 'failed','error' => $e->getMessage().' '.$e->getFile().' '.$e->getLine()], 200);
            //(new Slack(new Request(['title' => 'Error generateDocumentId', 'fields' => ['error'=>$e->getMessage(),'line'=>$e->getLine(),'trace'=>$e->getTraceAsString()]])))->send();
            $cwFactory = new CloudWatchLoggerFactory();
            $cwFactory->logger(json_encode(['module' => 'Avanse_digio', 'message' => $e->getMessage(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString()]));
            if($request->ajax()){
                return \response()->json(['status' => 'failed','error' => 'Something went wrong'], 200);
                //return \response()->json(['status' => 'failed','error' => 'Some error occurred'], 200);
            }
            return Redirect::to('/');
        }
    }

    public function updateDocumentId(Request $request) {
        try {
            if($request->ajax()){
                $inputs = $request->all();
                if(empty($inputs['code']) || empty($inputs['application_id'])) {
                    return \response()->json(['status' => 'failed','error' => 'Invalid inputs'], 200);
                }
                switch($inputs['code']) {
                    case 'signed':
                        if(empty($inputs['signed_by']) || empty($inputs['doc_id']) || empty($inputs['txn_id'])) {
                            return \response()->json(['status' => 'failed','error' => 'Invalid inputs'], 200);
                        }
                        if ($inputs['signed_by'] !== 'b' && $inputs['signed_by'] !== 'cb') {
                            return \response()->json(['status' => 'faireturn false;led','error' => 'Signing user could not be identified'], 200);
                        }
                        $lavObj = LoanAgreementVendor::checkIfEntryExistByDocNApp($inputs['application_id'], $inputs['doc_id']);
                        if (false === $lavObj) {
                            return \response()->json(['status' => 'failed','error' => 'Document not found'], 200);
                        }
                        if (false !== $lavObj = $lavObj->agreementSignedUpdate($inputs['signed_by'], $inputs['txn_id'])) {
                            // check if any sign is pending and send response
                            return \response()->json(['status' => 'OK', 'data' => ['sign_pending' => $lavObj->checkIfSigningPending()]], 200);
                        }
                        return \response()->json(['status' => 'failed','error' => 'Something went wrong'], 200);
                        break;
                    default:
                        return \response()->json(['status' => 'failed','error' => 'Invalid inputs'], 200);
                }

            }
            return \response()->json(['status' => 'failed','error' => 'Some error occured'], 200);

        } catch (\Exception $e){
            (new Slack(new Request(['title' => 'Error updateDocumentId', 'fields' => ['error'=>$e->getMessage(),'line'=>$e->getLine(),'trace'=>$e->getTraceAsString()]])))->send();
            if($request->ajax()){
                return \response()->json(['status' => 'failed','error' => 'Something went wrong'], 200);
                //return \response()->json(['status' => 'failed','error' => 'Some error occurred'], 200);
            }
            return Redirect::to('/');
        }
    }

    public function downloadDocumentId(Request $request) {
        try {
            if($request->ajax()){
                $inputs = $request->all();
                if(empty($inputs['application_id'])) {
                    return \response()->json(['status' => 'failed','error' => 'Invalid inputs'], 200);
                }
                $lavObj = '';
                if (!empty($inputs['doc_id'])) {
                    $lavObj = LoanAgreementVendor::checkIfEntryExistByDocNApp($inputs['application_id'], $inputs['doc_id']);
                } else {
                    $lavObj = LoanAgreementVendor::checkIfEntryExist($inputs['application_id']);
                }
                if ($lavObj instanceof LoanAgreementVendor) {
                    $out = $lavObj->checkIfSigningPending();
                    if (empty($out)) { // all users have signed it, no one is pending
                        $resp = $lavObj->downloadAgreement();
                        if ($resp) {
                            $this->sendEsignToCustomer($inputs['application_id']);
                            return \response()->json(['status' => 'OK', 'data' => []], 200);
                        }
                        return \response()->json(['status' => 'failed','error' => 'Some error occured'], 200);
                    } else {
                        return \response()->json(['status' => 'failed','error' => 'Agreement not signed by all users'], 200);
                    }
                } else {
                    return \response()->json(['status' => 'failed','error' => 'No application found'], 200);
                }
            }
            return \response()->json(['status' => 'failed','error' => 'Some error occured'], 200);

        } catch (\Exception $e){
            (new Slack(new Request(['title' => 'Error downloadDocumentId', 'fields' => ['error'=>$e->getMessage(),'line'=>$e->getLine(),'trace'=>$e->getTraceAsString()]])))->send();
            if($request->ajax()){
                return \response()->json(['status' => 'failed','error' => 'Something went wrong'], 200);
                //return \response()->json(['status' => 'failed','error' => 'Some error occurred'], 200);
            }
            return Redirect::to('/');
        }
    }

    public function getPincodeDetails(Request $request){

        if(!$request->get('pincode')){
            return \response()->json(["code" => 404], 404);
        }

        $query = 'select id, districtname as city, state from pincodes where pincode = '.$request->get('pincode');

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

        if(isset($queryData[0]->id)) {
            return \response()->json(["statusCode" => 'CF200', 'status' => 'OK', "data" => ["id" => $queryData[0]->id, "city" => $queryData[0]->city, "state" => $queryData[0]->state]], 200);
        }else{
            return \response()->json(["statusCode" => 'CF404', 'status' => 'FAIL'], 404);
        }
    }

    public function enachProcess(){
        $data = Input::all();

        $frequency = isset($data['b_type']) && $data['b_type'] == 0 ? 'monthly' : 'ADHO';
        $emandate_variant = isset($data['emandate_variant']) && $data['emandate_variant'] ? $data['emandate_variant'] : 'emandate';
        $until_cancelled = 0;
        if (isset($data['b_type']) && $data['b_type'] == 2){
            $until_cancelled = 1;
        }


        try {
            $bankid = isset($data['bankid']) ? $data['bankid'] : '';
            $bank_name = isset($data['bankname']) ? $data['bankname'] : '';
            $bank_ifsc_code = "";
            $bank_names_array = Config::get('constants.emandate_bank_list');
            $bank_names_list = array_keys($bank_names_array);

            if(in_array($bank_name ,$bank_names_list)) {
                $bank_ifsc_code = $bank_names_array[$bank_name];
            }
            if($bank_name == "Equitas Small Finance Bank"){
                $bank_ifsc_code = "ESFB";
            }
            if($bank_name == "HDFC Bank"){
                $bank_ifsc_code = "HDFC";
            }
            if($bank_name == "ICICI Bank"){
                $bank_ifsc_code = "ICIC";
            }
            if($bank_name == "IDBI Bank"){
                $bank_ifsc_code = "IBKL";
            }
            if($bank_name == "Indian Overseas Bank"){
                $bank_ifsc_code = "IOBA";
            }
            if($bank_name == "Tamilnad Mercantile Bank"){
                $bank_ifsc_code = "TMBL";
            }
            if($bank_name == "Ujjivan Small Finance Bank"){
                $bank_ifsc_code = "USFB";
            }

            $bankdetails = [
                'name' => isset($data['name']) ? $data['name'] : '',
                'ifsc_code' => isset($data['ifsccode']) ? $data['ifsccode'] : '',
                'bank_name' => $bank_name,
                'branch_name' => isset($data['branch']) ? $data['branch'] : '',
                'account_number' => isset($data['accountno']) ? $data['accountno'] : '',
                'account_type' => isset($data['accounttype']) ? $data['accounttype'] : '',
                'application_id' => isset($data['applicationid']) ? $data['applicationid'] : '',
                'bank_ifsc_code' => $bank_ifsc_code,
            ];
            if($bankid > 0){
                //Bank::where('id',$bankid)->update($bankdetails);
            }else {
                //Bank::insert($bankdetails);
            }


            $nach = new NachController();
            $nach->until_cancelled = $until_cancelled;
            $nach->retry_nach = isset($data['revised_link']);
            $nach->app_type = (Input::has('app_type') && Input::get('app_type') == 2) ? Input::get('app_type') : '';
            // if($data['lenderid'] == 11){
            //     $nachresponse = json_decode($nach->createMandateFromTransbnk($data['applicationid'],$emandate_variant,$frequency,$until_cancelled));
            // }else{
                $nachresponse = json_decode($nach->createMandate($data['applicationid'],$emandate_variant,$frequency,$until_cancelled));
            // }
//            $ConsumerDocument = New ConsumerDocument(New Request());
//
//            $manduateurl = json_decode($ConsumerDocument->createenach($data['applicationid']));

//            if(isset($nachresponse->url)){
//                \Session::flash('error', 'Incorrect Details for '.$manduateurl->error);
//                return redirect()->back();
//            }
            if(isset($nachresponse->url) && $nachresponse->url != "") {
                return redirect()->to($nachresponse->url);
            }else{
                $response = array();
                $response['is_home'] = true;
                $response['application_ids'] = $data['applicationid'];
                $response['bank'] = $data;
                $response['bank_names_list'] = $bank_names_list;

                $string = '';
                if (isset($nachresponse->error->param) && $nachresponse->error->param == 'nach_debit.reference1'){
                    $string = 'Invalid Account Number';;
                }

                $param = isset($nachresponse->error->error->param) ? ucfirst(str_replace('.',' ',str_replace('_',' ',$nachresponse->error->error->param.' '))) : '';
                $message = isset($nachresponse->error->error->message) ? $nachresponse->error->error->message: '';

                $response['isRetry'] = false;
                if($message == 'Amount must be between Rs 1.0 and Rs 100000.0'){
                    $response['isRetry'] = true;
                }

                $response['error'] = $message || $string || $param ? ($string ? $string : $param.$message) : 'Something went wrong went, Please try again later.';
                $response['b_type_status'] = $frequency;
                $req_base = json_decode($data['req_base'], 1);
                $nach->error_message = $response['error'];
                $nach->retry_nach = $response['isRetry'];
                $nach->app_type = (Input::has('app_type') && Input::get('app_type') == 2) ? Input::get('app_type') : '';
                return $nach->addEMandateConsumner($req_base['id'], $req_base['b_type'], $req_base['emandate_variant']);
                //return view('front.bankdetails',$response);
            }

        }catch (\Exception $e){
            (new Slack(new Request(['title' => 'LotusPay Error', 'fields' => ['error' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString()], 'group' => Slack::$STAGE_TESTING])))->send();
            $response = array();
            $response['is_home'] = true;
            $response['application_ids'] = $data['applicationid'];
            $response['lender_ids'] = $data['lenderid'];
            $response['bank'] = $data;
            $bank_names_array = Config::get('constants.emandate_bank_list');
            $bank_names_list = array_keys($bank_names_array);
            $response['bank_names_list'] = $bank_names_list;
            $param = isset($nachresponse->error->error->param) ? ucfirst(str_replace('.',' ',str_replace('_',' ',$nachresponse->error->error->param.' '))) : '';
            $response['error'] = isset($nachresponse->error->error->message) ? $response.' '.$nachresponse->error->error->message : 'Something went wrong went, Please try again later.';
            $response['b_type_status'] = $frequency;
            $response['app_type'] = (Input::has('app_type') && Input::get('app_type') == 2) ? Input::get('app_type') : '';
            return view('front.bankdetails',$response);
        }
    }
 }
