<?php

namespace App\Http\Controllers;

use App\_Slack;
use App\ABFL\Services\Services;
use App\ApplicationEMICalculation;
use App\Bank;
use App\BlackSoil;
use App\CampaignTracking;
use App\Careers;
use App\Comments;
use App\ConsumerApplication;
use App\ConsumerApplicationElement;
use App\Customers;
use App\HomevilleMandate;
use App\Http\Controllers\Admin\HomevilleController;
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\UserEventsLogs;
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 Illuminate\Support\Facades\File;
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\Avanse\Services\AvanseServices;
use App\KMGP2P;
use App\LoanHypothecation\LoanHypothecation;
use App\Shortio;
use App\DigioVKYC;
use App\BankValidation;
use App\Http\Controllers\WebhookController;

class FrontController extends Controller
{
    public $state = [];
    public $isInternal = false;
    /**
     * @var mixed
     */
    private $homeVilleMandateError = null;

    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 getInsurancePage(){
        return view('insurance');
    }

    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){

        $statement_blade = 'front.application.account_statement';
        $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();
        $rps_exists = RPS_Logs::where('application_id', $application_ids[0])->exists();
        $history = false;
        $secondaryStatus = ConsumerApplication::where('id', $application_ids[0])->first(['secondary_status']);

        $isRPSFetched = false;
        if(_env('LOAN_SCHEDULE_PYTHON') && $response = (new AccountingController())->getLoanScheduleUsingPythonService($application_ids[0])) {
            if (isset($response['status']) && $response['status'] != 'FAILED' || !isset($response['status'])) {
                $isRPSFetched = true;
                $history = $response;
            }
        }

        if($rps_exists || $isRPSFetched) {
            $history = (new RepaymentController())->getStatementDetails($application_ids[0], $history);
            $statement_blade = 'front.application.account_statement_v1';
        }else{
            (new LoanManagement())->paymentCalculate($application_ids[0], '', 'all');
            $history = $this->getPaymentHistory($hashed_id);
        }

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

        $application = ConsumerApplication::where('id', $application_ids[0])->first(['purpose']);
        $history['is_solar'] = isset($application->purpose) && $application->purpose == _env('SOLAR_CATEGORY_ID') ? 1 : 0;

        $imagePath = public_path('assets/front/img/homepage_banners/gradient_bg.png'); // Correct path in your project
        if (File::exists($imagePath)) {
            $imageData = base64_encode(File::get($imagePath));
            $history['bg_image_base64'] = 'data:image/png;base64,' . $imageData;
        } else {
            // Fallback or default color if image is not found
            $history['bg_image_base64'] = 'linear-gradient(to right, #634195, #F19F2F)';
        }

        $logoPath = public_path('assets/front/img/homepage_banners/CF_logo_violet.png');
        if (File::exists($logoPath)) {
            $logoData = base64_encode(File::get($logoPath));
            // Note: use 'image/jpeg' for .jpg files
            $history['lender']['logo'] = 'data:image/png;base64,' . $logoData;
        } else {
            // Fallback in case the logo is not found
            $history['lender']['logo'] = ''; 
        }

        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($statement_blade, $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' || $kycRule->kyc_type == '3') {
                $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', 'self_attested_co_aadhar')->orwhere('file_type', 'self_attested_co_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, $applicantType=1){

        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', 'bank_details_multiple', 'mandate','lender','activeOffer', 'foreclosed_transaction', 'application_additional')->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) {

            $process['proFormaInvoice'] = $applicationData->proFormaInvoice;
            $process['merchant_processing_collected'] = isset($applicationData->proFormaInvoice) ? $applicationData->proFormaInvoice->processing_fee_by_merchant : (isset($applicationData->merchant->is_collected) ? $applicationData->merchant->is_collected : 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 ($kmPFavailable = $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 = isset($applicationData->emi->legal_charges) ? $applicationData->emi->legal_charges : 0;
        
        // Legal charges
        if ($legal_charges_applicable_for_homeville || (($applicationData->lender_id == 2 || $applicationData->lender_id == 20) && isset($kmPFavailable) && $kmPFavailable)) {
            if ($legal_charges = isset($applicationData->emi->legal_charges) ? $applicationData->emi->legal_charges : 0) {
                $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 && $applicantType) {
            $appendString = env('APP_CONNECTION') == 0 
                ? "&post_approval=true&applicantType=" . $applicantType 
                : "?post_approval=true&applicantType=" . $applicantType;
            $fees['total_payment_link'] = $fees['total_payment_link'].$appendString;
        }

        $applicantMandate = DB::SelectOne("select id from mandate where consumer_application_id = $id and (applicant_type is null or applicant_type = 1) and status in ('active','submitted')");

        $coApplicantMandate = DB::SelectOne("select id from mandate where consumer_application_id = $id and applicant_type = 2 and status in ('active','submitted')");

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

        $bankDetails = $applicationData->bank_details_multiple;

        if($applicationData->lender_id == Singularity::$lender_id) {
            $mandate = HomevilleMandate::where('application_id', $id)->where('current_status', 'confirmed')->first(['id']);
        }

        $fees['set_auto_debit'] = null;
        $isHomevilleConfirmed = ($applicationData->lender_id == Singularity::$lender_id && isset($mandate->id));

        if(!isset($applicantMandate->id) && $applicationData->lender_id != Vivriti::$lender_id){
            $isFullAmount_hashed_id = $hashids->encode(2);
            $url = asset("enachrequest/id/" . $application_hashed_id . "/" . $isFullAmount_hashed_id);
            if($applicationData->lender_id == Singularity::$lender_id && !$isHomevilleConfirmed) {
                $homevilleController = (new HomevilleController(new Request(['id' => $id])))->generateNACHMandate();
                $homevilleControllerObject = $homevilleController->getData();
                if($homevilleControllerObject->status == 'OK') {
                    $url = $homevilleControllerObject->url ?? '';
                    $fees['set_auto_debit'] = $url;
                }else{
                    $this->homeVilleMandateError = $homevilleControllerObject;
                }
            }
            if($applicationData->lender_id != Singularity::$lender_id) {
                $fees['set_auto_debit'] = $url;
            }
        }

        $fees['co_applicant_required_for_mandate'] = 2; 
        // Co-applicant bank details checked, commented for now
        if (
            isset($applicationData->application_additional) &&
            isset($applicationData->application_additional->co_applicant_required_for_mandate) &&
            $applicationData->application_additional->co_applicant_required_for_mandate == 1
        ){
            $fees['co_applicant_required_for_mandate'] = 1;
            if(!isset($coApplicantMandate->id) && $applicationData->lender_id != Vivriti::$lender_id && $applicationData->lender_id != Singularity::$lender_id){

                if ($applicationData->co_applicant_name != '' || !empty($applicationData->co_applicant_name)) {
                    $url = asset("enachrequest/id/".$application_hashed_id."?type=2");
                    $fees['set_auto_debit_co_applicant'] = $url;
                }
            }
        }else{
            $fees['co_applicant_bank']['validation'] = true;
        }
        // $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 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 Blacksoil Capital 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 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 Blacksoil Capital 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');
        }elseif(isset($viewParameter['lender']->id) && $viewParameter['lender']->id == \App\BlackSoil::$lender_id){ // BlackSoil
            $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']];
            // This template is a complete BlackSoil document package: sanction letter,
            // consent letters, and the loan agreement. Rendering the sanction letter
            // separately duplicates it and corrupts the signing/PDF layout.
            $html = view('admin.documents.blacksoil.loan_agreement_v1', $save_agreement_document_details)->render();
            $pdf->loadHTML($html)->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 enachQuery($postApproval=true){

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

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

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

        // Bank validation added to post approval process
        if (!$postApproval || ($bankValidationStatus['result'] && $bankValidationStatus['percentage'] >= PostApprovalController::BANK_NAME_MATCH_PERCENTAGE)) {
            $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') : (isset($app_type)) ? $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['bankAddingStep'] = false;
                $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['bankAddingStep'] = true;
        $response['error'] = isset($bankValidationStatus['result']) && !$bankValidationStatus['result'] ? 'Bank Validation failed. If issue persists, please whatsapp/call at +918928769161' : ($app_type == 1 ? 'Bank acount holder name does not match the Applicant name. Please enter applicant bank details.' : 'Bank account holder name does not match the Co-Applicant name. Please enter co-applicant bank details.');
        $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 Blacksoil Capital 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', 'foreclosure_date');
            }, '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', isset($payment_dates[0]) && count($payment_dates) > 0 ? max($payment_dates) : strtotime($payment_date)),
                'last_payment_date' => isset($payment_dates[0]) && count($payment_dates) > 0 ? max($payment_dates) : $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->application_element->emi_pending ?? 0,
            '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;
        }

        $pre_part_payments = PaymentTransaction::where('application_id', $id)->where('payment_for', 'pre_part_payment')->whereNull('is_deleted_at')->get(['id','amount', 'mode', 'payment_date']);

        foreach($pre_part_payments as $pre_part_payment) {
            if (isset($pre_part_payment->id)) {
                $response['prePartPaymentAmount'] = $pre_part_payment->amount;
                $response['prePartPaymentMode'] = $pre_part_payment->mode;
                $response['prePartPaymentDate'] = date('Y-m-d', strtotime($pre_part_payment->payment_date));
                $response['isPrePartPayment'] = 1;
            }
        }

        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 sendCampaign($id = null){


        $application_ids = [124,
                                                325,
                                                586,
                                                662,
                                                881,
                                                922,
                                                1011,
                                                1215,
                                                1217,
                                                1242,
                                                1257,
                                                1671,
                                                1683,
                                                1689,
                                                1887,
                                                1940,
                                                1942,
                                                1943,
                                                1951,
                                                2016,
                                                2043,
                                                2055,
                                                2059,
                                                2064,
                                                2067,
                                                2094,
                                                2145,
                                                2147,
                                                2159,
                                                2160,
                                                2193,
                                                2194,
                                                2212,
                                                2236,
                                                2239,
                                                2269,
                                                2273,
                                                2274,
                                                2278,
                                                2295,
                                                2307,
                                                2330,
                                                2522,
                                                2566,
                                                2592,
                                                2606,
                                                2707,
                                                2735,
                                                2777,
                                                2801,
                                                2807,
                                                2819,
                                                2875,
                                                2910,
                                                2920,
                                                2940,
                                                2965,
                                                3001,
                                                3047,
                                                3068,
                                                3128,
                                                3140,
                                                3163,
                                                3169,
                                                3176,
                                                3178,
                                                3189,
                                                3191,
                                                3197,
                                                3223,
                                                3255,
                                                3293,
                                                3301,
                                                3326,
                                                3405,
                                                3481,
                                                3499,
                                                3518,
                                                3592,
                                                3604,
                                                3609,
                                                3650,
                                                3654,
                                                3673,
                                                3742,
                                                3786,
                                                3881,
                                                3912,
                                                3914,
                                                3921,
                                                3958,
                                                3968,
                                                3985,
                                                4059,
                                                4065,
                                                4068,
                                                4070,
                                                4126,
                                                4137,
                                                4138,
                                                4140,
                                                4169,
                                                4180,
                                                4275,
                                                4336,
                                                4372,
                                                4415,
                                                4425,
                                                4641,
                                                4651,
                                                4738,
                                                4774,
                                                4881,
                                                4914,
                                                4939,
                                                4948,
                                                4969,
                                                4990,
                                                5073,
                                                5169,
                                                5210,
                                                5260,
                                                5438,
                                                5508,
                                                5583,
                                                5640,
                                                5731,
                                                5765,
                                                5773,
                                                5790,
                                                5806,
                                                5850,
                                                5854,
                                                5859,
                                                5876,
                                                5978,
                                                6007,
                                                6025,
                                                6052,
                                                6054,
                                                6093,
                                                6157,
                                                6216,
                                                6232,
                                                6248,
                                                6282,
                                                6294,
                                                6317,
                                                6324,
                                                6376,
                                                6389,
                                                6433,
                                                6441,
                                                6460,
                                                6509,
                                                6510,
                                                6513,
                                                6551,
                                                6635,
                                                6649,
                                                6691,
                                                6702,
                                                6730,
                                                6775,
                                                6805,
                                                6813,
                                                6842,
                                                6848,
                                                6854,
                                                6914,
                                                6928,
                                                6931,
                                                6934,
                                                6975,
                                                6985,
                                                6992,
                                                7017,
                                                7082,
                                                7086,
                                                7142,
                                                7155,
                                                7193,
                                                7222,
                                                7224,
                                                7273,
                                                7282,
                                                7319,
                                                7323,
                                                7348,
                                                7360,
                                                7362,
                                                7376,
                                                7433,
                                                7441,
                                                7472,
                                                7486,
                                                7523,
                                                7529,
                                                7580,
                                                7613,
                                                7721,
                                                7726,
                                                7771,
                                                7783,
                                                7810,
                                                7811,
                                                7824,
                                                7869,
                                                7871,
                                                7883,
                                                7984,
                                                8151,
                                                8547,
                                                8558,
                                                8576,
                                                8612,
                                                8638,
                                                8662,
                                                8718,
                                                8770,
                                                8890,
                                                8919,
                                                8930,
                                                8945,
                                                8995,
                                                8997,
                                                9023,
                                                9035,
                                                9040,
                                                9103,
                                                9137,
                                                9151,
                                                9214,
                                                9229,
                                                9234,
                                                9261,
                                                9267,
                                                9281,
                                                9336,
                                                9341,
                                                9342,
                                                9392,
                                                9404,
                                                9409,
                                                9430,
                                                9450,
                                                9468,
                                                9477,
                                                9483,
                                                9543,
                                                9578,
                                                9636,
                                                9642,
                                                9707,
                                                9742,
                                                9852,
                                                9860,
                                                9865,
                                                9912,
                                                9967,
                                                10001,
                                                10005,
                                                10013,
                                                10026,
                                                10062,
                                                10101,
                                                10109,
                                                10134,
                                                10160,
                                                10220,
                                                10268,
                                                10285,
                                                10364,
                                                10367,
                                                10370,
                                                10415,
                                                10521,
                                                10523,
                                                10540,
                                                10556,
                                                10569,
                                                10586,
                                                10587,
                                                10600,
                                                10612,
                                                10615,
                                                10648,
                                                10689,
                                                10735,
                                                10762,
                                                10771,
                                                10772,
                                                10794,
                                                10865,
                                                10867,
                                                10932,
                                                10942,
                                                11093,
                                                11113,
                                                11115,
                                                11262,
                                                11270,
                                                11302,
                                                11337,
                                                11349,
                                                11373,
                                                11407,
                                                11408,
                                                11456,
                                                11460,
                                                11513,
                                                11515,
                                                11524,
                                                11537,
                                                11633,
                                                11683,
                                                12594,
                                                12619,
                                                12630,
                                                12667,
                                                12893,
                                                13142,
                                                13259,
                                                13269,
                                                13335,
                                                13349,
                                                13350,
                                                13413,
                                                13485,
                                                13490,
                                                13506,
                                                13526,
                                                13581,
                                                13702,
                                                13724,
                                                13807,
                                                13813,
                                                13840,
                                                13861,
                                                13886,
                                                14033,
                                                14148,
                                                14182,
                                                14222,
                                                16353,
                                                17145,
                                                17290,
                                                17420,
                                                17921,
                                                18016,
                                                18149,
                                                18559,
                                                18659,
                                                19338,
                                                19726,
                                                20288,
                                                20701,
                                                21692,
                                                21779,
                                                22031,
                                                22345,
                                                22576,
                                                22793,
                                                22827,
                                                22837,
                                                22842,
                                                23705,
                                                23893,
                                                24026,
                                                24181,
                                                24418,
                                                24709,
                                                24827,
                                                24859,
                                                24963,
                                                25075,
                                                25494,
                                                25694,
                                                26301,
                                                26753,
                                                26863,
                                                27267,
                                                27464,
                                                27599,
                                                27827,
                                                28193,
                                                28340,
                                                28545,
                                                28561,
                                                28633,
                                                28683,
                                                28860,
                                                29478,
                                                29650,
                                                31320,
                                                31550,
                                                31863,
                                                32111,
                                                33419,
                                                34627,
                                                35927,
                                                37520,
                                                39568,
                                                41845,
                                                42059,
                                                43124,
                                                43835,
                                                44445,
                                                44456,
                                                44487,
                                                45017,
                                                46331,
                                                46902,
                                                47126,
                                                48979,
                                                49622,
                                                50332,
                                                51008,
                                                51432,
                                                51484,
                                                51792,
                                                52176,
                                                52983,
                                                55987,
                                                59449,
                                                59454,
                                                59946,
                                                60159,
                                                60645,
                                                60743,
                                                61974,
                                                62292,
                                                62435,
                                                62460,
                                                62640,
                                                63292,
                                                63318,
                                                63434,
                                                63446,
                                                64555,
                                                65126,
                                                65388,
                                                65538,
                                                65978,
                                                66308,
                                                66451,
                                                66712,
                                                66826,
                                                67010,
                                                67088,
                                                67570,
                                                67614,
                                                67701,
                                                67731,
                                                67734,
                                                67824,
                                                68223,
                                                68260,
                                                68539,
                                                68760,
                                                69154,
                                                69388,
                                                69888,
                                                70768,
                                                70787,
                                                70788,
                                                70890,
                                                71093,
                                                71335,
                                                71406,
                                                71411,
                                                71588,
                                                71723,
                                                71840,
                                                71865,
                                                71898,
                                                71952,
                                                72233,
                                                72311,
                                                72513,
                                                72518,
                                                72594,
                                                72599,
                                                72645,
                                                72706,
                                                72774,
                                                72858,
                                                72972,
                                                73113,
                                                73117,
                                                73160,
                                                73186,
                                                73331,
                                                73367,
                                                73483,
                                                73497,
                                                73588,
                                                73592,
                                                73646,
                                                73754,
                                                73859,
                                                73863,
                                                73905,
                                                73945,
                                                73986,
                                                74134,
                                                74140,
                                                74235,
                                                74272,
                                                74280,
                                                74506,
                                                74517,
                                                74558,
                                                74588,
                                                74741,
                                                74798,
                                                74815,
                                                74976,
                                                75099,
                                                75274,
                                                75285,
                                                75313,
                                                75449,
                                                75475,
                                                75495,
                                                75507,
                                                75555,
                                                75654,
                                                75662,
                                                75684,
                                                75704,
                                                75818,
                                                75826,
                                                76029,
                                                76063,
                                                76064,
                                                76140,
                                                76241,
                                                76393,
                                                76437,
                                                76453,
                                                76510,
                                                76698,
                                                76708,
                                                76856,
                                                76890,
                                                76915,
                                                77006,
                                                77100,
                                                77106,
                                                77138,
                                                77215,
                                                77222,
                                                77228,
                                                77238,
                                                77355,
                                                77409,
                                                77480,
                                                77595,
                                                77803,
                                                78060,
                                                78067,
                                                78074,
                                                78086,
                                                78171,
                                                78188,
                                                78195,
                                                78223,
                                                78337,
                                                78409,
                                                78415,
                                                78468,
                                                78474,
                                                78511,
                                                78558,
                                                78605,
                                                78675,
                                                78716,
                                                78856,
                                                78910,
                                                78986,
                                                79029,
                                                79248,
                                                79341,
                                                79432,
                                                79462,
                                                79497,
                                                79552,
                                                79654,
                                                79778,
                                                79993,
                                                80011,
                                                80030,
                                                80061,
                                                80142,
                                                80159,
                                                80164,
                                                80379,
                                                80391,
                                                80399,
                                                80417,
                                                80568,
                                                80709,
                                                80775,
                                                80783,
                                                80848,
                                                80976,
                                                81044,
                                                81188,
                                                81223,
                                                81251,
                                                81292,
                                                81410,
                                                81530,
                                                81541,
                                                81591,
                                                81609,
                                                81646,
                                                81666,
                                                81709,
                                                81793,
                                                81847,
                                                81927,
                                                81994,
                                                82085,
                                                82096,
                                                82132,
                                                82162,
                                                82227,
                                                82236,
                                                82302,
                                                82307,
                                                82508,
                                                82535,
                                                82560,
                                                82571,
                                                82683,
                                                82686,
                                                82737,
                                                82764,
                                                82896,
                                                82907,
                                                82917,
                                                83037,
                                                83046,
                                                83136,
                                                83140,
                                                83190,
                                                83202,
                                                83244,
                                                83279,
                                                83308,
                                                83330,
                                                83372,
                                                83443,
                                                83475,
                                                83489,
                                                83508,
                                                83583,
                                                83594,
                                                83607,
                                                83650,
                                                83695,
                                                83737,
                                                83781,
                                                83951,
                                                84064,
                                                84114,
                                                84123,
                                                84142,
                                                84387,
                                                84540,
                                                84573,
                                                84663,
                                                84805,
                                                84809,
                                                84813,
                                                84819,
                                                84823,
                                                84859,
                                                84929,
                                                85036,
                                                85053,
                                                85068,
                                                85182,
                                                85199,
                                                85284,
                                                85338,
                                                85453,
                                                85489,
                                                85545,
                                                85562,
                                                85681,
                                                85688,
                                                85706,
                                                85820,
                                                85898,
                                                85907,
                                                86120,
                                                86136,
                                                86327,
                                                86335,
                                                86383,
                                                86437,
                                                86460,
                                                86530,
                                                86753,
                                                86808,
                                                86846,
                                                86918,
                                                87008,
                                                87025,
                                                87034,
                                                87087,
                                                87104,
                                                87253,
                                                87366,
                                                87394,
                                                87418,
                                                87735,
                                                87748,
                                                87938,
                                                87940,
                                                87952,
                                                87963,
                                                87984,
                                                88013,
                                                88046,
                                                88175,
                                                88224,
                                                88225,
                                                88258,
                                                88319,
                                                88407,
                                                88434,
                                                88461,
                                                88481,
                                                88499,
                                                88502,
                                                88655,
                                                88732,
                                                88833,
                                                88834,
                                                88876,
                                                88956,
                                                88987,
                                                88999,
                                                89105,
                                                89114,
                                                89139,
                                                89191,
                                                89235,
                                                89254,
                                                89264,
                                                89266,
                                                89267,
                                                89316,
                                                89404,
                                                89503,
                                                89638,
                                                89662,
                                                89792,
                                                89794,
                                                89818,
                                                89866,
                                                90038,
                                                90072,
                                                90130,
                                                90275,
                                                90285,
                                                90392,
                                                90484,
                                                90500,
                                                90589,
                                                90701,
                                                90784,
                                                90916,
                                                91026,
                                                91055,
                                                91153,
                                                91179,
                                                91240,
                                                91261,
                                                91385,
                                                91395,
                                                91458,
                                                91479,
                                                91480,
                                                91541,
                                                91575,
                                                91619,
                                                91630,
                                                91659,
                                                91661,
                                                91671,
                                                91764,
                                                91807,
                                                91839,
                                                91848,
                                                91850,
                                                91862,
                                                92002,
                                                92080,
                                                92096,
                                                92100,
                                                92144,
                                                92280,
                                                92292,
                                                92313,
                                                92317,
                                                92381,
                                                92462,
                                                92475,
                                                92492,
                                                92497,
                                                92646,
                                                92748,
                                                92777,
                                                92791,
                                                92795,
                                                92802,
                                                92897,
                                                92923,
                                                92938,
                                                92985,
                                                92999,
                                                93058,
                                                93131,
                                                93455,
                                                93505,
                                                93514,
                                                93517,
                                                93535,
                                                93539,
                                                93549,
                                                93584,
                                                93585,
                                                93604,
                                                93756,
                                                93797,
                                                93825,
                                                93826,
                                                93836,
                                                93840,
                                                93904,
                                                93930,
                                                93992,
                                                94124,
                                                94147,
                                                94208,
                                                94246,
                                                94278,
                                                94340,
                                                94368,
                                                94383,
                                                94385,
                                                94404,
                                                94465,
                                                94495,
                                                94523,
                                                94577,
                                                94598,
                                                94659,
                                                94766,
                                                94786,
                                                94787,
                                                94800,
                                                94802,
                                                94826,
                                                94892,
                                                95027,
                                                95095,
                                                95140,
                                                95204,
                                                95211,
                                                95254,
                                                95262,
                                                95336,
                                                95348,
                                                95378,
                                                95516,
                                                95743,
                                                95810,
                                                95829,
                                                95835,
                                                95967,
                                                95979,
                                                95992,
                                                96059,
                                                96099,
                                                96228,
                                                96239,
                                                96272,
                                                96305,
                                                96328,
                                                96356,
                                                96426,
                                                96443,
                                                96479,
                                                96492,
                                                96499,
                                                96528,
                                                96575,
                                                96676,
                                                96699,
                                                96711,
                                                96770,
                                                96776,
                                                96781,
                                                96793,
                                                96797,
                                                96813,
                                                96865,
                                                97058,
                                                97070,
                                                97085,
                                                97086,
                                                97099,
                                                97106,
                                                97211,
                                                97480,
                                                97488,
                                                97532,
                                                97554,
                                                97568,
                                                97575,
                                                97632,
                                                97670,
                                                97673,
                                                97738,
                                                97877,
                                                98088,
                                                98102,
                                                98104,
                                                98116,
                                                98178,
                                                98180,
                                                98209,
                                                98249,
                                                98269,
                                                98294,
                                                98343,
                                                98344,
                                                98403,
                                                98471,
                                                98566,
                                                98604,
                                                98636,
                                                98671,
                                                98674,
                                                98920,
                                                98944,
                                                98970,
                                                98983,
                                                99133,
                                                99265,
                                                99335,
                                                99336,
                                                99400,
                                                99472,
                                                99520,
                                                99544,
                                                99546,
                                                99560,
                                                99636,
                                                99643,
                                                99693,
                                                99804,
                                                99853,
                                                99863,
                                                99874,
                                                99908,
                                                99964,
                                                99972,
                                                100008,
                                                100084,
                                                100088,
                                                100125,
                                                100128,
                                                100184,
                                                100198,
                                                100220,
                                                100326,
                                                100364,
                                                100394,
                                                100475,
                                                100620,
                                                100647,
                                                100719,
                                                100745,
                                                100748,
                                                100924,
                                                100950,
                                                100951,
                                                100973,
                                                100989,
                                                101053,
                                                101062,
                                                101204,
                                                101212,
                                                101315,
                                                101316,
                                                101430,
                                                101462,
                                                101466,
                                                101587,
                                                101644,
                                                101752,
                                                101818,
                                                101872,
                                                102074,
                                                102248,
                                                102302,
                                                102310,
                                                102348,
                                                102408,
                                                102911,
                                                102932,
                                                102942,
                                                102964,
                                                103183,
                                                103207,
                                                103224,
                                                103554,
                                                103693,
                                                103737,
                                                104010,
                                                104031,
                                                104137,
                                                104144,
                                                104190,
                                                104234,
                                                104285,
                                                104542,
                                                104563,
                                                104592,
                                                104644,
                                                104705,
                                                104733,
                                                104785,
                                                104876,
                                                105031,
                                                105116,
                                                105309,
                                                105320,
                                                105532,
                                                105707,
                                                105784,
                                                105806,
                                                105823,
                                                106022,
                                                106146,
                                                106150,
                                                106233,
                                                106249,
                                                106473,
                                                106636,
                                                106639,
                                                106777,
                                                106928,
                                                106962,
                                                107453,
                                                107461,
                                                107464,
                                                107483,
                                                107567,
                                                107570,
                                                107615,
                                                107629,
                                                107632,
                                                107673,
                                                107797,
                                                107898,
                                                107939,
                                                108038,
                                                108159,
                                                108208,
                                                108209,
                                                108269,
                                                108309,
                                                108452,
                                                108511,
                                                108569,
                                                108698,
                                                108704,
                                                108705,
                                                108750,
                                                108817,
                                                108823,
                                                108861,
                                                108901,
                                                108935,
                                                108986,
                                                109499,
                                                109875,
                                                109877,
                                                109940,
                                                109969,
                                                110022,
                                                110026,
                                                110159,
                                                110301,
                                                110324,
                                                110696,
                                                110833,
                                                110862,
                                                111055,
                                                111161,
                                                111218,
                                                111654,
                                                111969,
                                                111989,
                                                112010,
                                                112098,
                                                112192,
                                                112202,
                                                112226,
                                                112254,
                                                112258,
                                                112327,
                                                112521,
                                                112616,
                                                112743,
                                                112746,
                                                112760,
                                                112872,
                                                113064,
                                                113066,
                                                113136,
                                                113269,
                                                113395,
                                                113625,
                                                113885,
                                                113912,
                                                114118,
                                                114160,
                                                114271,
                                                114274,
                                                114333,
                                                114644,
                                                114811,
                                                115045,
                                                115083,
                                                115115,
                                                115146,
                                                115149,
                                                115292,
                                                115591,
                                                115612,
                                                115682,
                                                115700,
                                                115787,
                                                115836,
                                                115839,
                                                115930,
                                                116069,
                                                116106,
                                                116141,
                                                116357,
                                                116369,
                                                116551,
                                                116648,
                                                116667,
                                                116670,
                                                116736,
                                                116749,
                                                116845,
                                                116902,
                                                116907,
                                                116981,
                                                117026,
                                                117124,
                                                117158,
                                                117163,
                                                117311,
                                                117365,
                                                117382,
                                                117460,
                                                117505,
                                                117569,
                                                117572,
                                                117592,
                                                117626,
                                                117705,
                                                117706,
                                                117915,
                                                117977,
                                                118055,
                                                118542,
                                                118550,
                                                118836,
                                                118956,
                                                119200,
                                                119202,
                                                119224,
                                                119421,
                                                119467,
                                                119480,
                                                119589,
                                                119746,
                                                119768,
                                                119779,
                                                119834,
                                                119943,
                                                120122,
                                                120186,
                                                120252,
                                                120261,
                                                120268,
                                                120553,
                                                120661,
                                                120940,
                                                120975,
                                                121013,
                                                121054,
                                                121057,
                                                121068,
                                                121253,
                                                121279,
                                                121310,
                                                121337,
                                                121446,
                                                121447,
                                                121520,
                                                121664,
                                                121686,
                                                121768,
                                                121772,
                                                121909,
                                                121991,
                                                122002,
                                                122024,
                                                122216,
                                                122265,
                                                122349,
                                                122365,
                                                122384,
                                                122472,
                                                122490,
                                                122497,
                                                122575,
                                                122621,
                                                122723,
                                                122725,
                                                122788,
                                                122874,
                                                122945,
                                                122952,
                                                122990,
                                                123140,
                                                123257,
                                                123360,
                                                123475,
                                                123533,
                                                123551,
                                                123634,
                                                123804,
                                                123808,
                                                123885,
                                                123887,
                                                124094,
                                                124182,
                                                124323,
                                                124441,
                                                124500,
                                                124546,
                                                124553,
                                                124607,
                                                124690,
                                                124791,
                                                124856,
                                                124912,
                                                124985,
                                                125062,
                                                125156,
                                                125240,
                                                125244,
                                                125446,
                                                125503,
                                                125548,
                                                125676,
                                                125682,
                                                125842,
                                                125951,
                                                125974,
                                                126002,
                                                126011,
                                                126078,
                                                126133,
                                                126223,
                                                126278,
                                                126292,
                                                126403,
                                                126503,
                                                126534,
                                                126550,
                                                126828,
                                                126930,
                                                127028,
                                                127053,
                                                127055,
                                                127153,
                                                127233,
                                                127241,
                                                127242,
                                                127328,
                                                127398,
                                                127440,
                                                127461,
                                                127708,
                                                127842,
                                                127856,
                                                127875,
                                                127895,
                                                128002,
                                                128374,
                                                128379,
                                                128428,
                                                128629,
                                                128827,
                                                128833,
                                                128931,
                                                128953,
                                                128972,
                                                129010,
                                                129058,
                                                129140,
                                                129201,
                                                129343,
                                                129355,
                                                129384,
                                                129416,
                                                129452,
                                                129508,
                                                129605,
                                                129664,
                                                129684,
                                                129754,
                                                129767,
                                                129837,
                                                129857,
                                                129886,
                                                129934,
                                                130046,
                                                130164,
                                                130166,
                                                130261,
                                                130403,
                                                130427,
                                                130441,
                                                130548,
                                                130563,
                                                130572,
                                                130654,
                                                130660,
                                                130943,
                                                131008,
                                                131037,
                                                131178,
                                                131182,
                                                131389,
                                                131847,
                                                131994,
                                                132292,
                                                132466,
                                                132469,
                                                132767,
                                                133101,
                                                133127,
                                                133278,
                                                133288,
                                                133394,
                                                133428,
                                                133484,
                                                133512,
                                                133618,
                                                133643,
                                                133678,
                                                133818,
                                                133918,
                                                133973,
                                                134057,
                                                134148,
                                                134168,
                                                134279,
                                                134408,
                                                134645,
                                                134711,
                                                135131,
                                                135369,
                                                135597,
                                                135614,
                                                136070,
                                                136250,
                                                136440,
                                                136463,
                                                136488,
                                                136783,
                                                137223,
                                                137573,
                                                137647,
                                                137766,
                                                137787,
                                                138145,
                                                138218,
                                                138225,
                                                138283,
                                                138654,
                                                138772,
                                                138860,
                                                139033,
                                                139087,
                                                139618,
                                                139958,
                                                140375,
                                                140420,
                                                140470,
                                                140499,
                                                140506,
                                                140606,
                                                140679,
                                                140855,
                                                140918,
                                                140941,
                                                140989,
                                                140995,
                                                141097,
                                                141319,
                                                141415,
                                                141516,
                                                141565,
                                                142052,
                                                142346,
                                                142421,
                                                142456,
                                                142669,
                                                142692,
                                                142820,
                                                143065,
                                                143295,
                                                143335,
                                                143618,
                                                143729,
                                                144539,
                                                144705,
                                                144810,
                                                145222,
                                                145233,
                                                145366,
                                                145381,
                                                145433,
                                                145470,
                                                145522,
                                                145572,
                                                145965,
                                                146029,
                                                146061,
                                                146264,
                                                146514,
                                                146679,
                                                146770,
                                                147144,
                                                147208,
                                                147586,
                                                147718,
                                                147763,
                                                147854,
                                                148329,
                                                148334,
                                                148425,
                                                148660,
                                                148677,
                                                148697,
                                                148811,
                                                148832,
                                                148856,
                                                148891,
                                                148960,
                                                149369,
                                                149382,
                                                149798,
                                                149967,
                                                150021,
                                                150095,
                                                150157,
                                                150939,
                                                151328,
                                                151741,
                                                151865,
                                                151990,
                                                151999,
                                                152137,
                                                152216,
                                                152344,
                                                152480,
                                                152608,
                                                152976,
                                                153077,
                                                153088,
                                                153175,
                                                153231,
                                                153380,
                                                153635,
                                                153790,
                                                153872,
                                                154209,
                                                154262,
                                                154536,
                                                154537,
                                                154633,
                                                154678,
                                                154780,
                                                154845,
                                                155275,
                                                155302,
                                                155338,
                                                155399,
                                                155461,
                                                155650,
                                                155742,
                                                155813,
                                                156128,
                                                156554,
                                                156807,
                                                156810,
                                                157126,
                                                157186,
                                                157236,
                                                157263,
                                                157356,
                                                157455,
                                                157503,
                                                157524,
                                                157528,
                                                157640,
                                                157705,
                                                157825,
                                                158143,
                                                158339,
                                                158389,
                                                158503,
                                                158562,
                                                158643,
                                                158646,
                                                158765,
                                                158787,
                                                158808,
                                                159059,
                                                159074,
                                                159165,
                                                159527,
                                                159898,
                                                159990,
                                                160542,
                                                160837,
                                                160851,
                                                160853,
                                                160971,
                                                161336,
                                                161684,
                                                161778,
                                                162180,
                                                162187,
                                                162229,
                                                162274,
                                                162329,
                                                162817,
                                                163509,
                                                163605,
                                                163719,
                                                163998,
                                                164342,
                                                164390,
                                                164406,
                                                164513,
                                                164775,
                                                164893,
                                                164911,
                                                165257,
                                                165603,
                                                166057,
                                                166377,
                                                166464,
                                                166768,
                                                166967,
                                                167192,
                                                167273,
                                                167819,
                                                167919,
                                                168023,
                                                168250,
                                                168368,
                                                168491,
                                                168536,
                                                168658,
                                                168673,
                                                168937,
                                                168977,
                                                169026,
                                                169076,
                                                169323,
                                                169410,
                                                169513,
                                                169562,
                                                169600,
                                                169681,
                                                169702,
                                                170141,
                                                170392,
                                                170417,
                                                170428,
                                                170530,
                                                170876,
                                                170983,
                                                170992,
                                                171241,
                                                171247,
                                                171260,
                                                171273,
                                                171293,
                                                171310,
                                                171382,
                                                171523,
                                                171532,
                                                171549,
                                                171552,
                                                171579,
                                                171596,
                                                171610,
                                                171617,
                                                171640,
                                                171651,
                                                171824,
                                                171835,
                                                171866,
                                                171885,
                                                171944,
                                                172073,
                                                172080,
                                                172220,
                                                172221,
                                                172276,
                                                172339,
                                                172355,
                                                172371,
                                                172434,
                                                172454,
                                                172467,
                                                172650,
                                                172706,
                                                172764,
                                                172840,
                                                172875,
                                                172877,
                                                172896,
                                                172897,
                                                172990,
                                                173025,
                                                173083,
                                                173111,
                                                173158,
                                                173182,
                                                173248,
                                                173306,
                                                173400,
                                                173423,
                                                173528,
                                                173538,
                                                173604,
                                                173610,
                                                173636,
                                                173951,
                                                173969,
                                                173984,
                                                173995,
                                                174005,
                                                174018,
                                                174043,
                                                174101,
                                                174105,
                                                174184,
                                                174195,
                                                174361,
                                                174385,
                                                174459,
                                                174522,
                                                174527,
                                                174554,
                                                174577,
                                                174585,
                                                174774,
                                                174775,
                                                174777,
                                                174802,
                                                174946,
                                                175091,
                                                175134,
                                                175149,
                                                175159,
                                                175284,
                                                175288,
                                                175395,
                                                175449,
                                                175450,
                                                175505,
                                                175513,
                                                175517,
                                                175537,
                                                175760,
                                                175766,
                                                175768,
                                                175820,
                                                175901,
                                                175908,
                                                175918,
                                                175943,
                                                175970,
                                                176027,
                                                176095,
                                                176117,
                                                176120,
                                                176150,
                                                176169,
                                                176185,
                                                176247,
                                                176308,
                                                176349,
                                                176488,
                                                176511,
                                                176602,
                                                176683,
                                                176827,
                                                177014,
                                                177103,
                                                177128,
                                                177177,
                                                177241,
                                                177255,
                                                177305,
                                                177343,
                                                177417,
                                                177418,
                                                177464,
                                                177494,
                                                177508,
                                                177525,
                                                177636,
                                                177679,
                                                177801,
                                                177807,
                                                177850,
                                                177851,
                                                177922,
                                                178093,
                                                178189,
                                                178208,
                                                178335,
                                                178355,
                                                178438,
                                                178440,
                                                178447,
                                                178474,
                                                178522,
                                                178523,
                                                178597,
                                                178616,
                                                178618,
                                                178632,
                                                178827,
                                                178918,
                                                178921,
                                                178926,
                                                178932,
                                                178950,
                                                178959,
                                                178972,
                                                179126,
                                                179155,
                                                179244,
                                                179289,
                                                179334,
                                                179356,
                                                179436,
                                                179472,
                                                179535,
                                                179542,
                                                179690,
                                                179705,
                                                179764,
                                                179790,
                                                179796,
                                                179943,
                                                179951,
                                                179963,
                                                179973,
                                                179988,
                                                180157,
                                                180185,
                                                180236,
                                                180255,
                                                180383,
                                                180425,
                                                180487,
                                                180709,
                                                180710,
                                                180728,
                                                180772,
                                                180885,
                                                181051,
                                                181096,
                                                181154,
                                                181214,
                                                181236,
                                                181387,
                                                181401,
                                                181443,
                                                181470,
                                                181487,
                                                181582,
                                                181696,
                                                181805,
                                                181839,
                                                182152,
                                                182207,
                                                182234,
                                                182326,
                                                182464,
                                                182609,
                                                182653,
                                                182677,
                                                182829,
                                                182854,
                                                182927,
                                                182932,
                                                182962,
                                                182990,
                                                183007,
                                                183076,
                                                183095,
                                                183152,
                                                183241,
                                                183347,
                                                183452,
                                                183480,
                                                183545,
                                                183622,
                                                183741,
                                                183883,
                                                183888,
                                                183936,
                                                184016,
                                                184127,
                                                184218,
                                                184232,
                                                184239,
                                                184363,
                                                184396,
                                                184546,
                                                185063,
                                                185065,
                                                185141,
                                                185169,
                                                185272,
                                                185278,
                                                185303,
                                                185589,
                                                185610,
                                                185618,
                                                185668,
                                                185737,
                                                185991,
                                                185998,
                                                186127,
                                                186260,
                                                186341,
                                                186349,
                                                186363,
                                                186481,
                                                186548,
                                                186716,
                                                186782,
                                                186820,
                                                186884,
                                                187100,
                                                187152,
                                                187174,
                                                187197,
                                                187272,
                                                187280,
                                                187308,
                                                187312,
                                                187448,
                                                187506,
                                                187533,
                                                187553,
                                                187713,
                                                187782,
                                                187783,
                                                187793,
                                                187794,
                                                187804,
                                                187879,
                                                188051,
                                                188058,
                                                188126,
                                                188157,
                                                188200,
                                                188221,
                                                188285,
                                                188337,
                                                188369,
                                                188372,
                                                188405,
                                                188492,
                                                188514,
                                                188616,
                                                188658,
                                                188809,
                                                188930,
                                                188969,
                                                188974,
                                                189257,
                                                189258,
                                                189291,
                                                189534,
                                                189566,
                                                189764,
                                                189793,
                                                189811,
                                                190064,
                                                190232,
                                                190235,
                                                190254,
                                                190345,
                                                190382,
                                                190429,
                                                190563,
                                                190716,
                                                190854,
                                                190867,
                                                190910,
                                                190976,
                                                190983,
                                                191052,
                                                191228,
                                                191256,
                                                191274,
                                                191291,
                                                191424,
                                                191434,
                                                191581,
                                                191681,
                                                191692,
                                                191693,
                                                191726,
                                                191784,
                                                191840,
                                                191924,
                                                192234,
                                                192317,
                                                192371,
                                                192405,
                                                192427,
                                                192428,
                                                192482,
                                                192561,
                                                192569,
                                                192651,
                                                192737,
                                                193023,
                                                193040,
                                                193087,
                                                193275,
                                                193303,
                                                193312,
                                                193555,
                                                193695,
                                                193699,
                                                193745,
                                                193794,
                                                193811,
                                                193872,
                                                193936,
                                                193999,
                                                194059,
                                                194174,
                                                194176,
                                                194187,
                                                194192,
                                                194349,
                                                194376,
                                                194403,
                                                194427,
                                                194450,
                                                194675,
                                                194715,
                                                194755,
                                                194853,
                                                194865,
                                                194923,
                                                195067,
                                                195113,
                                                195216,
                                                195255,
                                                195328,
                                                195355,
                                                195514,
                                                195590,
                                                195609,
                                                195610,
                                                195664,
                                                195708,
                                                195727,
                                                195796,
                                                196194,
                                                196237,
                                                196311,
                                                196397,
                                                196616,
                                                196625,
                                                196700,
                                                196718,
                                                196773,
                                                196900,
                                                197019,
                                                197256,
                                                197279,
                                                197316,
                                                197325,
                                                197366,
                                                197566,
                                                197576,
                                                197580,
                                                198014,
                                                198076,
                                                198146,
                                                198159,
                                                198174,
                                                198175,
                                                198205,
                                                198249,
                                                198341,
                                                198355,
                                                198415,
                                                198560,
                                                198585,
                                                198592,
                                                198643,
                                                198733,
                                                198740,
                                                198772,
                                                198814,
                                                198821,
                                                198870,
                                                198914,
                                                198917,
                                                198971,
                                                199004,
                                                199046,
                                                199053,
                                                199122,
                                                199176,
                                                199230,
                                                199254,
                                                199285,
                                                199428,
                                                199507,
                                                199629,
                                                199986,
                                                200092,
                                                200111,
                                                200127,
                                                200397,
                                                200524,
                                                200566,
                                                200611,
                                                200632,
                                                200686,
                                                200754,
                                                200936,
                                                201066,
                                                201080,
                                                201294,
                                                201315,
                                                201316,
                                                201407,
                                                201433,
                                                201542,
                                                201809,
                                                201882,
                                                201928,
                                                202076,
                                                202292,
                                                202369,
                                                202386,
                                                202432,
                                                202458,
                                                202463,
                                                202622,
                                                202756,
                                                202920,
                                                202934,
                                                203019,
                                                203031,
                                                203108,
                                                203140,
                                                203193,
                                                203310,
                                                203329,
                                                203680,
                                                203713,
                                                203865,
                                                204052,
                                                204208,
                                                204259,
                                                204305,
                                                204372,
                                                204401,
                                                204471,
                                                204493,
                                                204540,
                                                204563,
                                                204583,
                                                204744,
                                                204783,
                                                204884,
                                                204983,
                                                205143,
                                                205251,
                                                205400,
                                                205434,
                                                205444,
                                                205484,
                                                205532,
                                                205561,
                                                205720,
                                                205727,
                                                205944,
                                                205953,
                                                206073,
                                                206170,
                                                206199,
                                                206259,
                                                206310,
                                                206404,
                                                206413,
                                                206486,
                                                206488,
                                                206583,
                                                206738,
                                                206743,
                                                206748,
                                                206794,
                                                206901,
                                                206947,
                                                206978,
                                                206993,
                                                207012,
                                                207054,
                                                207110,
                                                207203,
                                                207271,
                                                207488,
                                                207515,
                                                207534,
                                                207550,
                                                207575,
                                                207639,
                                                207651,
                                                207706,
                                                207767,
                                                207772,
                                                207789,
                                                207797,
                                                207828,
                                                207842,
                                                207897,
                                                207930,
                                                207995,
                                                208001,
                                                208004,
                                                208014,
                                                208028,
                                                208259,
                                                208473,
                                                208514,
                                                208581,
                                                208620,
                                                208640,
                                                208892,
                                                208906,
                                                208960,
                                                208964,
                                                209066,
                                                209088,
                                                209372,
                                                209381,
                                                209393,
                                                209401,
                                                209464,
                                                209519,
                                                209662,
                                                209880,
                                                210056,
                                                210085,
                                                210195,
                                                210355,
                                                210369,
                                                210400,
                                                210429,
                                                210447,
                                                210638,
                                                210657,
                                                210678,
                                                210701,
                                                210712,
                                                210714,
                                                210839,
                                                210872,
                                                210892,
                                                210930,
                                                210974,
                                                211108,
                                                211129,
                                                211179,
                                                211229,
                                                211277,
                                                211576,
                                                211687,
                                                211729,
                                                211766,
                                                211895,
                                                211942,
                                                211956,
                                                211976,
                                                212231,
                                                212270,
                                                212367,
                                                212392,
                                                212397,
                                                212409,
                                                212473,
                                                212484,
                                                212549,
                                                212783,
                                                212787,
                                                212832,
                                                212880,
                                                212943,
                                                212974,
                                                213002,
                                                213009,
                                                213072,
                                                213170,
                                                213175,
                                                213206,
                                                213234,
                                                213248,
                                                213262,
                                                213294,
                                                213316,
                                                213337,
                                                213360,
                                                213402,
                                                213435,
                                                213504,
                                                213554,
                                                213660,
                                                213685,
                                                213736,
                                                213876,
                                                213899,
                                                213901,
                                                213950,
                                                213979,
                                                214003,
                                                214004,
                                                214010,
                                                214046,
                                                214110,
                                                214164,
                                                214222,
                                                214234,
                                                214243,
                                                214247,
                                                214294,
                                                214303,
                                                214411,
                                                214413,
                                                214474,
                                                214476,
                                                214494,
                                                214502,
                                                214590,
                                                214638,
                                                214647,
                                                214651,
                                                214691,
                                                214721,
                                                214798,
                                                214941,
                                                214951,
                                                214994,
                                                215000,
                                                215131,
                                                215151,
                                                215232,
                                                215288,
                                                215312,
                                                215335,
                                                215338,
                                                215365,
                                                215414,
                                                215437,
                                                215443,
                                                215484,
                                                215492,
                                                215501,
                                                215560,
                                                215588,
                                                215596,
                                                215607,
                                                215620,
                                                215679,
                                                215684,
                                                215701,
                                                215734,
                                                215762,
                                                215784,
                                                215807,
                                                215814,
                                                215864,
                                                215891,
                                                215894,
                                                215895,
                                                216043,
                                                216057,
                                                216068,
                                                216107,
                                                216137,
                                                216163,
                                                216198,
                                                216221,
                                                216233,
                                                216265,
                                                216274,
                                                216277,
                                                216363,
                                                216396,
                                                216500,
                                                216552,
                                                216576,
                                                216706,
                                                216727,
                                                216748,
                                                216842,
                                                216846,
                                                216859,
                                                216860,
                                                217104,
                                                217105,
                                                217107,
                                                217134,
                                                217350,
                                                217356,
                                                217359,
                                                217423,
                                                217457,
                                                217583,
                                                217585,
                                                217611,
                                                217694,
                                                217725,
                                                217733,
                                                217832,
                                                217971,
                                                218057,
                                                218156,
                                                218179,
                                                218245,
                                                218246,
                                                218286,
                                                218310,
                                                218352,
                                                218364,
                                                218407,
                                                218417,
                                                218423,
                                                218449,
                                                218507,
                                                218545,
                                                218564,
                                                218691,
                                                218706,
                                                218742,
                                                218938,
                                                218941,
                                                218972,
                                                218981,
                                                218993,
                                                219041,
                                                219042,
                                                219146,
                                                219229,
                                                219237,
                                                219319,
                                                219462,
                                                219490,
                                                219547,
                                                219647,
                                                219686,
                                                219718,
                                                219722,
                                                219799,
                                                219815,
                                                219877,
                                                219897,
                                                219909,
                                                219935,
                                                219948,
                                                220005,
                                                220012,
                                                220043,
                                                220163,
                                                220286,
                                                220290,
                                                220295,
                                                220315,
                                                220317,
                                                220337,
                                                220456,
                                                220489,
                                                220499,
                                                220509,
                                                220533,
                                                220540,
                                                220741,
                                                220750,
                                                220765,
                                                220767,
                                                220903,
                                                220949,
                                                220970,
                                                221042,
                                                221089,
                                                221130,
                                                221151,
                                                221170,
                                                221239,
                                                221241,
                                                221249,
                                                221272,
                                                221318,
                                                221334,
                                                221363,
                                                221442,
                                                221493,
                                                221507,
                                                221528,
                                                221577,
                                                221581,
                                                221586,
                                                221654,
                                                221721,
                                                221722,
                                                221723,
                                                221791,
                                                221794,
                                                221857,
                                                221902,
                                                221905,
                                                221994,
                                                222010,
                                                222020,
                                                222023,
                                                222048,
                                                222091,
                                                222150,
                                                222175,
                                                222179,
                                                222196,
                                                222220,
                                                222250,
                                                222253,
                                                222295,
                                                222301,
                                                222311,
                                                222389,
                                                222419,
                                                222431,
                                                222439,
                                                222553,
                                                222631,
                                                222681,
                                                222688,
                                                222691,
                                                222699,
                                                222733,
                                                222747,
                                                222792,
                                                222841,
                                                222849,
                                                222855,
                                                222992,
                                                223009,
                                                223010,
                                                223036,
                                                223052,
                                                223062,
                                                223130,
                                                223166,
                                                223196,
                                                223225,
                                                223287,
                                                223303,
                                                223322,
                                                223427,
                                                223635,
                                                223674,
                                                223729,
                                                223778,
                                                223809,
                                                223843,
                                                223853,
                                                223854,
                                                223942,
                                                223991,
                                                224008,
                                                224011,
                                                224024,
                                                224030,
                                                224130,
                                                224176,
                                                224201,
                                                224262,
                                                224283,
                                                224374,
                                                224383,
                                                224405,
                                                224410,
                                                224429,
                                                224440,
                                                224452,
                                                224493,
                                                224497,
                                                224500,
                                                224504,
                                                224511,
                                                224538,
                                                224601,
                                                224635,
                                                224768,
                                                224809,
                                                224840,
                                                224844,
                                                224914,
                                                225001,
                                                225027,
                                                225056,
                                                225101,
                                                225116,
                                                225216,
                                                225256,
                                                225294,
                                                225327,
                                                225351,
                                                225386,
                                                225391,
                                                225408,
                                                225513,
                                                225521,
                                                225534,
                                                225555,
                                                225578,
                                                225585,
                                                225603,
                                                225622,
                                                225646,
                                                225697,
                                                225768,
                                                225785,
                                                225833,
                                                225842,
                                                225907,
                                                225966,
                                                225974,
                                                226012,
                                                226086,
                                                226096,
                                                226141,
                                                226179,
                                                226213,
                                                226262,
                                                226467,
                                                226486,
                                                226534,
                                                226572,
                                                226609,
                                                226623,
                                                226635,
                                                226700,
                                                226706,
                                                226708,
                                                226771,
                                                226797,
                                                226833,
                                                226847,
                                                226871,
                                                226927,
                                                226950,
                                                226960,
                                                226999,
                                                227004,
                                                227006,
                                                227050,
                                                227083,
                                                227125,
                                                227195,
                                                227206,
                                                227212,
                                                227275,
                                                227321,
                                                227367,
                                                227414,
                                                227506,
                                                227524,
                                                227603,
                                                227619,
                                                227640,
                                                227665,
                                                227684,
                                                227757,
                                                227764,
                                                227919,
                                                227980,
                                                228070,
                                                228071,
                                                228079,
                                                228158,
                                                228172,
                                                228180,
                                                228236,
                                                228245,
                                                228251,
                                                228301,
                                                228306,
                                                228343,
                                                228344,
                                                228395,
                                                228452,
                                                228454,
                                                228470,
                                                228472,
                                                228478,
                                                228567,
                                                228623,
                                                228624,
                                                228637,
                                                228640,
                                                228705,
                                                228749,
                                                228766,
                                                228867,
                                                228925,
                                                228974,
                                                229023,
                                                229031,
                                                229048,
                                                229055,
                                                229060,
                                                229132,
                                                229251,
                                                229253,
                                                229309,
                                                229375,
                                                229427,
                                                229473,
                                                229723,
                                                229758,
                                                229885,
                                                229923,
                                                230055,
                                                230076,
                                                230103,
                                                230105,
                                                230190,
                                                230192,
                                                230257,
                                                230322,
                                                230360,
                                                230584,
                                                230655,
                                                230690,
                                                230741,
                                                230868,
                                                230986,
                                                231048,
                                                231054,
                                                231101,
                                                231102,
                                                231172,
                                                231230,
                                                231279,
                                                231302,
                                                231317,
                                                231342,
                                                231353,
                                                231372,
                                                231415,
                                                231466,
                                                231478,
                                                231488,
                                                231543,
                                                231548,
                                                231591,
                                                231595,
                                                231646,
                                                231650,
                                                231683,
                                                231688,
                                                231742,
                                                231749,
                                                231810,
                                                231857,
                                                231869,
                                                231966,
                                                232021,
                                                232034,
                                                232036,
                                                232089,
                                                232121,
                                                232123,
                                                232183,
                                                232193,
                                                232248,
                                                232258,
                                                232328,
                                                232355,
                                                232373,
                                                232413,
                                                232555,
                                                232579,
                                                232652,
                                                232691,
                                                232766,
                                                232785,
                                                232877,
                                                232899,
                                                233166,
                                                233307,
                                                233375,
                                                233432,
                                                233696,
                                                233751,
                                                233813,
                                                233837,
                                                233849,
                                                233919,
                                                233982,
                                                234211,
                                                234235,
                                                234252,
                                                234317,
                                                234329,
                                                234354,
                                                234524,
                                                234628,
                                                234697,
                                                234715,
                                                234783,
                                                234950,
                                                234983,
                                                235053,
                                                235094,
                                                235182,
                                                235187,
                                                235200,
                                                235263,
                                                235281,
                                                235484,
                                                235485,
                                                235492,
                                                235663,
                                                235679,
                                                235731,
                                                235751,
                                                235767,
                                                235826,
                                                235910,
                                                235922,
                                                235943,
                                                235982,
                                                235992,
                                                236003,
                                                236005,
                                                236010,
                                                236035,
                                                236133,
                                                236185,
                                                236220,
                                                236386,
                                                236402,
                                                236479,
                                                236502,
                                                236510,
                                                236527,
                                                236566,
                                                236568,
                                                236635,
                                                236735,
                                                236793,
                                                236795,
                                                236853,
                                                236904,
                                                236936,
                                                236942,
                                                236944,
                                                236946,
                                                236949,
                                                237040,
                                                237063,
                                                237076,
                                                237086,
                                                237108,
                                                237144,
                                                237156,
                                                237179,
                                                237270,
                                                237319,
                                                237387,
                                                237419,
                                                237423,
                                                237482,
                                                237571,
                                                237586,
                                                237587,
                                                237643,
                                                237680,
                                                237715,
                                                237908,
                                                237925,
                                                237943,
                                                237965,
                                                238047,
                                                238056,
                                                238062,
                                                238074,
                                                238079,
                                                238128,
                                                238370,
                                                238483,
                                                238510,
                                                238579,
                                                238630,
                                                238631,
                                                238718,
                                                238749,
                                                238750,
                                                238793,
                                                238865,
                                                238899,
                                                238936,
                                                238967,
                                                238979,
                                                239056,
                                                239084,
                                                239241,
                                                239242,
                                                239308,
                                                239354,
                                                239465,
                                                239474,
                                                239491,
                                                239597,
                                                239618,
                                                239649,
                                                239650,
                                                239691,
                                                239735,
                                                239747,
                                                239762,
                                                239773,
                                                239832,
                                                239849,
                                                239868,
                                                239944,
                                                240150,
                                                240156,
                                                240347,
                                                240452,
                                                240508,
                                                240538,
                                                240661,
                                                240759,
                                                240804,
                                                240858,
                                                240923,
                                                240927,
                                                240939,
                                                240970,
                                                241099,
                                                241117,
                                                241156,
                                                241170,
                                                241282,
                                                241397,
                                                241406,
                                                241433,
                                                241476,
                                                241622,
                                                241651,
                                                241729,
                                                241784,
                                                241922,
                                                241936,
                                                242022,
                                                242129,
                                                242165,
                                                242255,
                                                242287,
                                                242376,
                                                242441,
                                                242466,
                                                242544,
                                                242622,
                                                242662,
                                                242706,
                                                242780,
                                                242792,
                                                242813,
                                                242888,
                                                243152,
                                                243155,
                                                243163,
                                                243220,
                                                243346,
                                                243359,
                                                243419,
                                                243460,
                                                243477,
                                                243527,
                                                243553,
                                                243615,
                                                243625,
                                                243713,
                                                244019,
                                                244033,
                                                244201,
                                                244213,
                                                244239,
                                                244296,
                                                244387,
                                                244419,
                                                244462,
                                                244463,
                                                244479,
                                                244564,
                                                244669,
                                                244764,
                                                244832,
                                                244888,
                                                244889,
                                                245017,
                                                245122,
                                                245265,
                                                245277,
                                                245280,
                                                245375,
                                                245423,
                                                245456,
                                                245466,
                                                245474,
                                                245540,
                                                245560,
                                                245712,
                                                245734,
                                                245829,
                                                245898,
                                                246034,
                                                246103,
                                                246106,
                                                246113,
                                                246145,
                                                246377,
                                                246400,
                                                246499,
                                                246669,
                                                246741,
                                                246788,
                                                246795,
                                                246802,
                                                246886,
                                                246951,
                                                246989,
                                                247036,
                                                247053,
                                                247078,
                                                247082,
                                                247170,
                                                247312,
                                                247458,
                                                247468,
                                                247471,
                                                247483,
                                                247509,
                                                247516,
                                                247648,
                                                247649,
                                                247714,
                                                247742,
                                                247770,
                                                247815,
                                                247840,
                                                247867,
                                                247875,
                                                247884,
                                                247953,
                                                247956,
                                                247983,
                                                248039,
                                                248060,
                                                248066,
                                                248137,
                                                248217,
                                                248264,
                                                248266,
                                                248283,
                                                248317,
                                                248321,
                                                248343,
                                                248426,
                                                248459,
                                                248491,
                                                248537,
                                                248568,
                                                248596,
                                                248725,
                                                248729,
                                                248746,
                                                248903,
                                                248933,
                                                248974,
                                                248989,
                                                249079,
                                                249196,
                                                249297,
                                                249298,
                                                249305,
                                                249337,
                                                249447,
                                                249469,
                                                249548,
                                                249595,
                                                249860,
                                                249951,
                                                249970,
                                                250067,
                                                250097,
                                                250135,
                                                250136,
                                                250200,
                                                250421,
                                                250514,
                                                250528,
                                                250620,
                                                250624,
                                                250678,
                                                250694,
                                                250745,
                                                250753,
                                                250790,
                                                250806,
                                                250822,
                                                250841,
                                                250858,
                                                250939,
                                                251052,
                                                251230,
                                                251283,
                                                251454,
                                                251680,
                                                251803,
                                                251879,
                                                251892,
                                                251912,
                                                252062,
                                                252070,
                                                252304,
                                                252366,
                                                252619,
                                                252655,
                                                253001,
                                                253197,
                                                253259,
                                                253264,
                                                253327,
                                                253335,
                                                253471,
                                                253595,
                                                253685,
                                                253698,
                                                253699,
                                                253706,
                                                253767,
                                                253771,
                                                253833,
                                                253834,
                                                253839,
                                                253940,
                                                253943,
                                                254097,
                                                254280,
                                                254341,
                                                254391,
                                                254591,
                                                254643,
                                                254654,
                                                254690,
                                                254758,
                                                254770,
                                                254789,
                                                255257,
                                                255745,
                                                255914,
                                                255953,
                                                256008,
                                                256142,
                                                256155,
                                                256322,
                                                256327,
                                                256423,
                                                256507,
                                                256515,
                                                256647,
                                                256796,
                                                256922,
                                                256941,
                                                257131,
                                                257494,
                                                257589,
                                                257652,
                                                257708,
                                                257741,
                                                257959,
                                                258206,
                                                258375,
                                                258464,
                                                258668,
                                                258703,
                                                258869,
                                                259187,
                                                259431,
                                                259437,
                                                259567,
                                                259751,
                                                259807,
                                                259906,
                                                259909,
                                                259938,
                                                259979,
                                                260003,
                                                260321,
                                                260348,
                                                260382,
                                                260471,
                                                260509,
                                                260583,
                                                260590,
                                                260731,
                                                260861,
                                                260893,
                                                261176,
                                                261210,
                                                261276,
                                                261413,
                                                261473,
                                                261474,
                                                261492,
                                                261560,
                                                261637,
                                                261786,
                                                261813,
                                                261827,
                                                261868,
                                                262011,
                                                262054,
                                                262072,
                                                262190,
                                                262331,
                                                262394,
                                                262406,
                                                262460,
                                                262545,
                                                262600,
                                                262637,
                                                262678,
                                                262904,
                                                262930,
                                                262995,
                                                263234,
                                                263624,
                                                263633,
                                                263647,
                                                263705,
                                                263727,
                                                263753,
                                                263760,
                                                263928,
                                                264192,
                                                264201,
                                                264236,
                                                264252,
                                                264339,
                                                264410,
                                                264418,
                                                264542,
                                                264665,
                                                264944,
                                                264953,
                                                264991,
                                                265204,
                                                265257,
                                                265280,
                                                265361,
                                                265384,
                                                265438,
                                                265610,
                                                265621,
                                                265669,
                                                265719,
                                                265728,
                                                265779,
                                                265856,
                                                265905,
                                                265930,
                                                266010,
                                                266097,
                                                266191,
                                                266227,
                                                266266,
                                                266282,
                                                266310,
                                                266427,
                                                266443,
                                                266474,
                                                266709,
                                                266784,
                                                266926,
                                                267009,
                                                267067,
                                                267074,
                                                267250,
                                                267470,
                                                267767,
                                                268005,
                                                268147,
                                                268261,
                                                268415,
                                                268505,
                                                268548,
                                                268739,
                                                268804,
                                                268823,
                                                268844,
                                                268897,
                                                268902,
                                                268950,
                                                269003,
                                                269100,
                                                269142,
                                                269219,
                                                269316,
                                                269349,
                                                269520,
                                                269549,
                                                269566,
                                                269630,
                                                269652,
                                                269763,
                                                269768,
                                                269893,
                                                269897,
                                                269927,
                                                269969,
                                                270018,
                                                270066,
                                                270142,
                                                270209,
                                                270231,
                                                270275,
                                                270308,
                                                270342,
                                                270514,
                                                270529,
                                                270609,
                                                270709,
                                                270710,
                                                270773,
                                                270792,
                                                270809,
                                                270954,
                                                271005,
                                                271067,
                                                271068,
                                                271131,
                                                271208,
                                                271612,
                                                271702,
                                                271726,
                                                271748,
                                                271895,
                                                271920,
                                                271937,
                                                272089,
                                                272141,
                                                272213,
                                                272386,
                                                272673,
                                                272702,
                                                272720,
                                                272785,
                                                272891,
                                                273027,
                                                273083,
                                                273104,
                                                273455,
                                                273566,
                                                273642,
                                                273686,
                                                273729,
                                                273936,
                                                274029,
                                                274030,
                                                274217,
                                                274309,
                                                274693,
                                                275045,
                                                275124,
                                                275239,
                                                275524,
                                                276354,
                                                276379,
                                                276393,
                                                276524,
                                                276532,
                                                276728,
                                                276746,
                                                276814,
                                                277004,
                                                277037,
                                                277254,
                                                277636,
                                                279694,
                                                279782,
                                                279947,
                                                280502,
                                                280908,
                                                280983,
                                                282353,
                                                246312,
                                                271038,
                                                243987,
                                                263004,
                                                270319,
                                                270697,
                                                270741,
                                                271091,
                                                273207,
                                                274543,
                                                275288,
                                                279061,
                                                279067,
                                                279720,
                                                280466,
                                                234110,
                                                261512,
                                                264563,
                                                265215,
                                                270156,
                                                270646,
                                                270922,
                                                271815,
                                                274623,
                                                274716,
                                                274736,
                                                276926,
                                                276948,
                                                276992,
                                                278504,
                                                279831,
                                                270559,
                                                272550,
                                                243357,
                                                260658,
                                                270598,
                                                270774,
                                                242893,
                                                258835,
                                                269048,
                                                270740,
                                                270829,
                                                271183,
                                                271399,
                                                271499,
                                                272261,
                                                273903,
                                                276316,
                                                279737,
                                                262631,
                                                264509,
                                                270060,
                                                270467,
                                                271452,
                                                262159,
                                                270782];

        $applications = ConsumerApplication::whereIn('id', $application_ids)->get(['id', 'name', 'email']);

        foreach($applications as $application){
            if(strlen($application->email)) {
                $hashids = new Hashids('Creditfair by CS', 20);
                $application_id_enc = $hashids->encode($application->id);

                $link = asset('pre_approval/eligibility_check/' . $application_id_enc);

                $email = $application->email;

                $message = '<a href="' . $link . '"><img src="' . asset('assets/front/img/pre_approved_img.png') . '" style="width: 100%;"/></a></br></br>
Dear ' . ucwords($application->name) . ',</br></br>
We’re pleased to inform you that you are eligible for a pre-approved personal loan of ₹75,000.</br>

To proceed further with the loan process, please click on the link shared below:</br></br>

 <div><a style="padding: 12px; background: #f2a027; border-radius: 8px; color: white; text-decoration: none;" href="' . $link . '">Proceed</a></div></br>

The process is fully digital and takes only a few minutes.</br></br>

Loan eligibility, amount, and final approval are subject to verification and applicable terms and conditions.</br></br>';

                \Mail::send('emails.reminders.basic_reminder',
                    [
                        'body' => $message,
                        'lender_id' => '',
                        'hideLogo' => 1
                    ]
                    , function ($message) use ($email) {
                        $message->to($email)->subject("You're Eligible for a Pre-Approved Personal Loan of ₹75,000");
                    });
            }
        }
    }

    public function captureLocation($id, Request $request){
        $hashids = new Hashids('Creditfair by CS', 20);
        $hashID =  $hashids->decode($id);

        if($hashID && isset($hashID[0])){
            $application_id = $hashID[0];
            $application = ConsumerApplication::where('id', $application_id)->first(['name']);
        }else{
            return \redirect()->to('/');
        }

        return view('front.location_tracking', [
            'id' => $id, 'data' => $request->get('data'), 'name' => $application->name ?? '-',
            'text_content_approval_message' => ''
        ]);
    }

    public function updateUserAction(Request $request){
        $status = 'FAIL';
        $message = 'There is some issue. Please try after sometime.';
        $redirect = '';

        $data = json_decode(base64_decode($request->get('data')), 1);

        $tracker_event = $data['tracker_event'] ?? '';
        $lat = $data['lat'] ?? '';
        $lng = $data['lng'] ?? '';
        $source = $data['source'] ?? '';
        $event = $data['event'] ?? '';

        if ($tracker_event && $lat && $lng && $source){
            try {

                $hashids = new Hashids('Creditfair by CS', 20);
                $hashID =  $hashids->decode($tracker_event);
                $application_id = 0;
                if($hashID && isset($hashID[0])){
                    $application_id = $hashID[0];
                }

                if($application_id) {
                    $application = ConsumerApplication::where('id', $application_id)->first(['id', 'applicant_id']);
                    if (isset($application->id)) {
                        UserEventsLogs::insert([
                            '_id' => $application_id,
                            'id_type' => 'application_id',
                            'service' => 'payment_link',
                            'event' => $event,
                            'latitude' => $lat,
                            'longitude' => $lng,
                            'additional_param' => json_encode($data),
                            'created_at' => Carbon::now()->toDateTimeString()
                        ]);

                        $status = 'OK';
                        $message = 'success';
                        $redirect = 'paytm/'.$request->get('id').'?data='.$request->get('data');
                    }
                }
            }catch (\Exception $e){

            }
        }

        if (!$lat || !$lng) {
            $message = 'There is some issue with the location, Please give the permission and retry';
        }
        return \response()->json(['status' => $status,  'message' => $message, 'redirect' => $redirect]);
    }

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

        /*if ($redirectLocationCapture = $this->captureLocation($id, $request)){
            return $redirectLocationCapture;
        }*/

        $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] : "";
            $pre_part_payment_type = isset($amount_hash[3]) ? $amount_hash[3] : "";

            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";
        }

        if ($request->has('applicantType')) {
            $data['MERC_UNQ_REF'] = $data['MERC_UNQ_REF']."_".$request->get('applicantType');
        }

        $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" || $payment_for == "pre_part_payment" || $payment_for == "settlement_payment") {
            $onlinepayment->purpose = $payment_for;
        }else {
            $onlinepayment->purpose = "EMI";
        }
        $onlinepayment->amount = $data['TXN_AMOUNT'];
        $onlinepayment->status = "Pending";
        $onlinepayment->foreclosure_date = $foreclosure_date;
        $onlinepayment->pre_part_payment_type = isset($pre_part_payment_type) && !empty($pre_part_payment_type) ? $pre_part_payment_type : 0;
        $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);

                        $refParts = explode("_", $paytmParams['MERC_UNQ_REF']);
                        $type = isset($refParts[4]) ? $refParts[4] : 1; 
                        return redirect()->to('esign/' . $hashed_id . '?type='.$type.'&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);
                        $refParts = explode("_", $paytmParams['MERC_UNQ_REF']);
                        $type = isset($refParts[4]) ? $refParts[4] : 1; 
                        return redirect()->to('esign/' . $hashed_id . '?type='.$type.'&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);
                $refParts = explode("_", $paytmParams['MERC_UNQ_REF']);
                $type = isset($refParts[4]) ? $refParts[4] : 1; 
                return redirect()->to('esign/' . $hashed_id . '?type='.$type.'&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', ''));
        }elseif ($lender_id == BlackSoil::$lender_id ) {
            $api = new Api(_env('BLACKSOILRAZORPAYKEY', ''), _env('BLACKSOILRAZORPAYSECRET', ''));
        }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);
        }
    }
 }
