<?php

namespace App\Http\Controllers\Admin;

use App\ABFL\Services\Services;
use App\AcceptableDataReason;
use App\BlackSoil;
use App\NameMatchService;
use App\AccountAggregator;
use App\AccountAggregatorModel;
use App\AdvisorLogs;
use App\APIWrapper\Headers;
use App\APIWrapper\Wrapper;
use App\ApplicationDeviation;
use App\ApplicationEMICalculation;
use App\ApplicationEMICalculationLock;
use App\ApprovalRule;
use App\ApprovalStatusLog;
use App\CacheExistingCustomer;
use App\JsonBreApprovalStatusLog;
use App\LoanDecisionApprovedAmount;
use App\DecisionTable;
use App\ApprovedPincodeLists;
use App\AutoRejectLogs;
use App\Capri;
use App\ApiResponse;
use App\ConsentLog;
use App\DisbursementOffers;
use App\LoanHypothecation\DigioHypothecation;
use App\PSUService;
use App\RiskBasedInterestRate;
use Illuminate\Support\Collection;
use App\DisbursementOffersData;
use App\DisbursementRequests;
use App\Avanse\DataModels\AvanseCustomer;
use App\Avanse\DataModels\AvanseDisbursementInstruction;
use App\Avanse\DataModels\AvanseFinance;
use App\Avanse\Processes\AvanseCreditPolicy;
use App\Avanse\Processes\AvanseProcesses;
use App\Avanse\Processes\PolicyAttributes;
use App\Avanse\Services\AvanseServices;
use App\AvanseCreateCustomer;
use App\AvanseMasterData;
use App\AvanseRequests;
use App\BNPL;
use App\Listeners\V1\MailerLogs;
use App\MerchantCategoryKYCRules;
use App\MerchantCategoryLegalCharges;
// use App\DocumentDetails;
use App\Bureau;
use App\CampaignsJobProvider;
use App\CFOneFinConfig;
use App\CFPayoutDirectTransfer;
use App\ChargedInvoices;
use App\ChecklistExceptionLogs;
use App\Console\Commands\AvansePaymentProcessJob;
use App\CommunicationMapping;
use App\CommunicationService;
use App\Console\Commands\RQConsumerListener;
use App\Console\Commands\TallyBridge;
use App\Console\Commands\TallySettlementJobs;
use App\Console\Commands\VendorWebhook;
use App\ContentLogger;
use App\CoronaHotspot;
use App\CPVMailer;
use App\Customers;
use App\DeviationType;
use App\DocumentDetails;
use App\DigioVKYC;
use App\ekycIntegration;
use App\EPFUANLookup;
use App\Http\Controllers\Admin\DecentroController;
use App\Events\V1\EventAvansePaymentProcess;
use App\Events\V1\EventMConnectWebhook;
use App\Events\V1\EventMonthlySubventionInvoice;
use App\Events\V1\EventPostCreateFinance;
use App\Events\V1\EventPostDisbursementInstruction;
use App\Events\V1\EventPostBureauPull;
use App\Events\V1\EventRejectApplication;
use App\Events\V1\EventTableOfOffer;
use App\Events\V1\EventVendorWebhook;
use App\finBoxIntegration;
use App\FLDGCategory;
use App\FraudReport;
use App\FraudReportBankTransactions;
use App\FraudReportCategoryStatus;
use App\GCMRegistraion;
use App\GSTPANData;
use App\Http\Controllers\AnalyticsController;
use App\Http\Controllers\ConsumerAPI\ConsumerApiController;
use App\Http\Controllers\Kabootar;
use App\HypervergeVideo;
use App\HypervergeVideoAttribute;
use App\HypervergeWebhook;
use App\ImagePDFSignature;
use App\Imports\Corona;
use App\Imports\RBIBlacklistImport;
use App\JMService\JMServices;
use App\KarzaAPI;
use App\LendBox;
use App\LendBoxLSP;
use App\LenderCategoryValidation;
use App\LiabilityLog;
use App\Lib\Common\Utility;
use App\LoanHypothecation\LoanHypothecation;
use App\MandatoryDocumentListLogs;
use App\MerchantBank;
use App\MerchantRiskMitigation;
use App\MerchantWhitelistLender;
use App\Method\ABFL\ABFLMethods;
use App\Method\OneFin\Payload\Payload;
use App\Model\Prediction;
use App\Moratorium;
use App\OneFinModel;
use App\OneFinService;
use App\OnfidoIntegration;
use App\OtpManager;
use App\PageConfig;
use App\Payout\PayoutAPI;
use App\Payout\PayTMSettlement;
use App\PayoutCF\CF_Logs;
use App\PayoutCF\PayoutCFAPI;
use App\PayoutPreserve;
use App\PayoutStatus;
use App\MerchantCategoryScripts;
use App\KYCDetails;
use App\php;
use App\BankValidation;
use App\BounceTransactions;
use App\CallLogs;
use App\CancellationDisbursement;
use App\CoApplicateValidationLog;
use App\CollectionManger;
use App\ApproverData;
use App\Console\Commands\AdvanceReminders;
use App\Console\Commands\BasicReminders;
use App\Couriers;
use App\CreditLine;
use App\DigitalSignDetails;
use App\Disbursement;
use App\DisbursementLogs;
use App\DocumentRule;
use App\DocumentRuleLog;
use App\DocumentSets;
use App\EmailCheck;
use App\EmiPayment;
use App\Equifax;
use App\Exotel\Exotel;
use App\Exotel\ExotelServices;
use App\Exports\Exporter;
use App\FCMNotification;
use App\FCMResponse;
use App\FinBit;
use App\Pirimid;
use App\FinBitData;
use App\GPSLogs;
use App\Http\Controllers\Couriers\CouriersController;
use App\Http\Controllers\FrontController;
use App\Http\Controllers\MerchantApiController;
use App\Http\Controllers\TestingController;
use App\Http\Controllers\Admin\MetabaseController;
use App\Http\Controllers\Tracker\LocationTracker;
use App\Http\Middleware\MongoMiddleware;
use App\Imports\PaymentFile;
use App\JobProvider;
use App\Jobs;
use App\JWTAccess;
use App\LenderBank;
use App\LoanManagement;
use App\Logs;
use App\MandateLogs;
use App\MandateStatusLog;
use App\MongoDB\Mongo;
use App\MultiStageDisbursement;
use App\NachSupportedBank;
use App\NachService;
use App\PaymentMakerChecker;
use App\Pincode;
use App\PreApprovalLog;
use App\PreviousLoans;
use App\Products;
use App\ProjectLead\ProjectLeadFiles;
use App\PromiseToPay;
use App\RawQuery;
use App\RBIBlacklist;
use App\RevocationList;
use App\RiskBasedConfiguration;
use App\RPS_Logs;
use App\SanctionAmountLogs;
use App\Settlement;
use App\Shortio;
use App\Singularity\Singularity;
use App\Slack;
use App\StaticPage;
use App\Tally\JournalVoucher;
use App\Tally\Ledger;
use App\Locations;
use App\NegativeArea;
use App\OnlinePayment;
use App\PaymentEmi;
use App\PWAApplicationForm;
use App\PaymentTransaction;
use App\SMSLogs;
use App\Tally\Tally;
use App\Tally\TallyConnector;
use App\Tally\TallyJobs;
use App\Tally\TallyListener;
use App\TallyJobsListener;
use App\TelecomData;
use App\TelecomDetails;
use App\Templates;
use App\TradeAdvanceDisbursement;
use App\UserAvailability;
use App\UserEmails;
use App\UserGeolocation;
use App\UserNearestStations;
use App\UserTypes;
use App\UtilityValidation;
use App\Utkarsh\Utkarsh;
use App\UtkarshVKYC;
use App\VendorApiCredentials;
use App\Vivriti;
use App\WalletConfiguration;
use App\Webhook;
use App\WhatsApp;
use Firebase\JWT\JWT;
use function foo\func;
use function GuzzleHttp\Psr7\str;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Lang;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\URL;
use MathPHP\Finance;
use PHPMailer\PHPMailer\Exception;
use Razorpay\Api\Api;
use App\Approval;
use App\Bank;
use App\Centers;
use App\Comments;
use App\Company;
use App\Checklist;
use App\CSV;
use App\Exports\RBLNach;
use App\Grades\Grades;
use App\Http\Controllers\Grade\GradeController;
use App\Imports\RBLNachImports;
use App\Invoices;
use App\Lenders;
use App\Mailer;
use App\MerchantFiles;
use App\Nach;
use App\CaseReviewRequest;
use App\ConsumerApplication;
use App\ConsumerApplicationElement;
use App\ConsumerApplicationAdditional;
use App\ConsumerApplicationFiles;
use App\ConsumerVerification;
use App\CreditReport;
use App\FOIR;
use App\Http\Controllers\ApiController;
use App\Http\Controllers\PostApprovalController;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Service\ServiceController;
use App\Http\Controllers\TestScripts\TestScripts;
use App\Mandate;
use App\Merchant;
use App\MerchantCategory;
use App\MerchantLocation;
use App\MerchantOffers;
use App\NegativeProfile;
use App\OCRRecognition;
use Illuminate\Support\Facades\Route;
use App\ProFormaInvoice;
use App\Reminders;
use App\ScoreCard;
use App\StateModel;
use App\StatusLogs;
use App\SecondaryStatusLogs;
use App\Trello;
use App\User;
use Aws\S3\Exception\S3Exception;
use Aws\S3\S3Client;
use Carbon\Carbon;
use Doctrine\DBAL\Schema\Schema;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Session;
use League\Flysystem\Filesystem;
use Illuminate\Http\File;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Input;
use Hashids\Hashids;
use Illuminate\Support\Facades\Storage;
use League\Flysystem\AwsS3v3\AwsS3Adapter;
use Maatwebsite\Excel\Facades\Excel;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use Illuminate\Http\UploadedFile;
use App\Model\LoanAgreementVendor;
use App\Events\V1\EventPostCreateCustomer;
use App\AvanseCreateFinance;
use App\Avanse\Services\SubService\CreateFinance;
use App\Events\V1\EventPostFormCompleted;
use App\AvanseNoc;
use App\Events\V1\EventAvanseNoc;
use App\KarzaVideo;
use App\KarzaVideoAttribute;
use App\KarzaVideoWebhook;
use App\Exports\ExporterMultipleSheet;
use App\Exports\BureauExporter;
use App\AgencyApplication;
use App\Method\Decentro\DecentroMethods;
use App\DecentroCkyc;
use App\Logging\CloudWatchLoggerFactory;
use App\Imports\ExcelImport;
use App\Imports\TestImport;
use Illuminate\Support\Facades\Validator;
use App\KMGP2P;
use App\LoanHypothecationModel;
use App\KMGP2PBorrowerReg;
use App\EpfFailureLog;
use App\Http\Controllers\Admin\autoBRE;
use ZipArchive;
use App\Http\Controllers\WebhookController;
use App\Http\Controllers\JsonBREController;
use App\QueueLog;
use App\Events\V1\EventAutoDecision;
use App\Http\Controllers\Grade\AutoRejection;
use App\Http\Controllers\ConsentController;

class ConsumerApplicationController extends Controller
{
    const NUM_OF_RECORDS_PER_PAGE = 10;
    const VKYC_VENDOR = "karza"; // karza, hyperverge
    public static $risk_category = [
        "V" => "Credit Score Above benchmark score",
        "A" => "Non-Resident Customers",
        "B" => "High Net-worth Individuals without an occupation track record of more than 3 years",
        "C" => "Trust, Charitable Organizations, Non-Government Organizations (NGO), Organizations receiving donations",
        "D" => "Companies having close family shareholdings and beneficial ownerships",
        "E" => "Firms with Sleeping Partners",
        "F" => "Politically Exposed Persons (PEPs) of Indian/Foreign Origin",
        "G" => "Non Face to Face Customers",
        "H" => "A person with a dubious reputation as per public information available",
        "I" => "A salaried applicant with variable income/unstructured income receiving salary in Cheque",
        "J" => "Salaried applicant working with Private Limited Companies, Proprietary, Partnership Firms",
        "K" => "Self-employed professionals other than HNIs",
        "L" => "Self-employed customers with sound business and profitable track record for a reasonable period",
        "M" => "High Net Worth Individuals with an occupation track record of more than 3 years",
        "N" => "High Net Worth Individuals",
        "O" => "Entities whose identities and source of wealth can be easily identified",
        "P" => "All other Persons not covered under the above two categories",
        "Q" => "Salaried employees with well-defined salary structures for over 5 years",
        "R" => "People working with government-owned Companies, regulators and statutory bodies, MNCs, rated Companies Public Sector Units, Public Limited Companies, etc.",
        "S" => "People of lower economic strata with small account balances and low turnover",
        "T" => "People working with Public Sector Units",
        "U" => "People working with reputed Public Limited Companies and Multinational Companies",
        "W" => ""
    ];

    public $decision_reason_list = [1 => 'Case not doable due to Age limit',
        2 => 'Case not fit into any lenders policies',
        3 => 'Case not approved as new mechant 1st case',
        4 => 'Atta Chakki case not doable in any lender',
        5 => 'Not doable in any lender due to 30+ DPD or not fitting in Bureau Criteria',
        6 => 'Not doable in any lender due to high Foir',
        7 => 'Documents not available as per lender',
        8 => 'Power saving policy not available in any lender',
        9 => 'Pension income not accepted in any lender',
        10 => 'NRI Applicant not doable in any lender',
        11 => 'Type of Business not doable in any lender',
        12 => 'Low Bureau score as per lender policy',
        13 => 'NOC or E-bill arrears payment can’t share before approval',
        14 => 'Other'
    ];

    private $verifications;
    public $status = array();
    public $otherWebhookEvents = array();
    private $current_status;
    public $isInternal = false;
    public $sendReturnStatus = false;
    public $viewReturn = false;
    public $isRoot = true;
    private $paymentData = [];
    private $pendingDoc = [];
    private $invoiceCounter = true;
    public $isRedirect = false;
    public $disbursementThrough = false;
    private $getCibilReportApplication = [];
    private $auto_approved_status = false;
    private $isMultiLender = false;
    public $gradeStatusAutoDecision = false;
    public $legalChargesProcessingFee = 100;
    public $isEquifaxEnabled = true;
    /**
     * @var bool
     */
    private $homevill_callback = false;
    private $utilityValidationSucceeded = false;

    public function __construct()
    {
//        $this->status = ['incomplete' => 'incomplete', 'form completed' => 'form completed', 'in-process' => 'in-process','waiting for documents' => 'waiting for documents','waiting for decision' => 'waiting for decision', 'approved' => 'approved', 'disbursement checklist done' => 'disbursement checklist done', 'ready for disbursement' => 'ready for disbursement', 'disbursed' => 'disbursed','cancellation in-process' => 'cancellation in-process','cancelled' => 'cancelled', 'nach registered' => 'nach registered', 'closed' => 'closed', 'rejected' => 'rejected', 'aborted' => 'aborted'];
//
//        $this->statusarray = array('incomplete form' => array('form completed', 'rejected', 'aborted'), 'form completed' => array('in-process', 'rejected', 'aborted'), 'in-process' => array('waiting for documents', 'waiting for decision', 'rejected', 'aborted'), 'waiting for documents' => array('waiting for decision','in-process', 'rejected', 'aborted'), 'waiting for decision' => array('waiting for documents','in-process', 'rejected', 'aborted'), 'approved' => array('disbursement checklist done', 'rejected', 'aborted'), 'disbursement checklist done' => array('approved', 'rejected', 'aborted'), 'ready for disbursement' => array('disbursement checklist done', 'rejected', 'aborted'), 'disbursed' => array('nach registered','closed','cancellation in-process'),'cancellation in-process'=>array('cancelled'),'cancelled' => array(), 'nach registered' => array('closed','cancellation in-process'), 'closed' => array(), 'rejected' => array('in-process'), 'aborted' => array('in-process'));
//
//        $this->arraygroup = array('incomplete form' => 'form completed', 'form completed' => 'form completed', 'in-process' => 'in-process', 'waiting for documents' => 'in-process', 'waiting for decision' => 'in-process', 'approved' => 'approved', 'disbursement checklist done' => 'approved', 'ready for disbursement' => 'approved', 'disbursed' => 'disbursed', 'nach registered' => 'nach registered', 'closed' => 'closed', 'cancellation in-process'=> 'cancelled','cancelled' => 'cancelled', 'rejected' => 'rejected', 'aborted' => 'aborted');
//
//        $this->helptext = array('incomplete form' => 'Form Completed ->In Process', 'form completed' => 'In Process', 'in-process' => 'Gather Documents ->Complete Verification Checklist', 'waiting for documents' => 'Gather Documents -> Complete Verification Checklist', 'waiting for decision' => 'Get Decision From Credit Team','approved' => 'Get Agreement Signed ->Get Nach Registered ->Pro-Forma ->disbursement checklist done', 'disbursement checklist done' => 'Get Disbursement Approval', 'ready for disbursement' => 'Get Disbursed', 'disbursed' => 'Get Nach Activated','nach registered' => 'Keep a track of EMI', 'closed' => 'Keep it touch for more services', 'rejected' => 'Return to In process?', 'aborted' => 'Return to In process?','cancelled' => 'Refunded or Cancelled by Merchant','cancellation in-process' =>  "Co-ordinate with merchant for cancellation");
//        $this->pendingDoc = array('in-process' => ['Bureau' => 'equifax_report', 'Pan'=>'pan_card', 'Pan Valid'=>'panvalidation', 'Add'=>'address', 'Tenure'=>'foir', 'Co-applicant Income' => 'co_applicant_for_income', 'Co-applicant Sign' => 'co_applicant_for_signing'], 'waiting for documents' => ['Bureau' => 'equifax_report', 'Pan'=>'pan_card', 'Pan Valid'=>'panvalidation', 'Add'=>'address', 'Tenure'=>'foir', 'Co-applicant Income' => 'co_applicant_for_income', 'Co-applicant Sign' => 'co_applicant_for_signing'], 'approved' => ['Bank Valid'=>'bank_details', 'Sign Proforma'=>'proforma', 'Nach'=>'nach', 'Chq'=>'security_cheques', 'E-Sign'=>'agreement'], 'disbursed' => ['courier'=>'courier','Reg Nach'=>'reg_nach'], 'waiting for decision'=>['pending decision'=>'pending_decision']);
//
//        $this->statusreversearray = array('incomplete form' => array(''), 'form completed' => array('incomplete form'), 'in-process' => array('form completed', 'incomplete form', 'rejected', 'aborted'), 'waiting for documents' => array('form completed', 'incomplete form', 'rejected', 'aborted', 'in-process'), 'waiting for decision' => array('form completed', 'incomplete form', 'rejected', 'aborted', 'in-process', 'waiting for documents'), 'approved' => array('form completed', 'incomplete form', 'rejected', 'aborted', 'in-process', 'waiting for documents', 'waiting for decision'), 'disbursement checklist done' => array('form completed', 'incomplete form', 'rejected', 'aborted', 'in-process', 'waiting for documents', 'waiting for decision', 'approved'), 'ready for disbursement' => array('form completed', 'incomplete form', 'rejected', 'aborted', 'in-process', 'waiting for documents', 'waiting for decision', 'approved','disbursement checklist done'),'disbursed' => array('form completed', 'incomplete form', 'rejected', 'aborted', 'in-process', 'waiting for documents', 'waiting for decision', 'approved','disbursement checklist done','ready for disbursement','cancelled','cancellation in-process'),'nach registered' => array('form completed', 'incomplete form', 'rejected', 'aborted', 'in-process', 'waiting for documents', 'waiting for decision', 'approved','disbursement checklist done','ready for disbursement','disbursed','cancelled','cancellation in-process'), 'closed' => array('form completed', 'incomplete form', 'rejected', 'aborted', 'in-process', 'waiting for documents', 'waiting for decision', 'approved','disbursement checklist done','ready for disbursement','disbursed','nach registered','cancelled','cancellation in-process'),'rejected' => array('form completed', 'incomplete form', 'rejected', 'aborted', 'in-process', 'waiting for documents', 'waiting for decision', 'approved','disbursement checklist done','ready for disbursement','cancelled','cancellation in-process'), 'aborted' => array('form completed', 'incomplete form', 'rejected', 'aborted', 'in-process', 'waiting for documents', 'waiting for decision', 'approved','disbursement checklist done','ready for disbursement','cancelled','cancellation in-process'), 'cancelled' => array('form completed', 'incomplete form', 'rejected', 'aborted', 'in-process', 'waiting for documents', 'waiting for decision', 'approved','disbursement checklist done','ready for disbursement','disbursed','nach registered','cancelled','closed','cancellation in-process'), 'cancellation in-process' => array('form completed', 'incomplete form', 'rejected', 'aborted', 'in-process', 'waiting for documents', 'waiting for decision', 'approved','disbursement checklist done','ready for disbursement','disbursed','nach registered','closed','cancellation in-process'));
//          $this->DocsStatus = ['waiting for decision' => ['equifax_report', 'pan_card', 'panvalidation', 'address', 'foir'], 'approved' => ['approved_amount'], 'disbursement checklist done' => ['generate_emi', 'sanction_letter', 'pro_forma_invoice', 'agreement', 'nach','proforma','bank_details','security_cheques']];

        $this->status = ['incomplete' => 'incomplete', 'form completed' => 'form completed', 'in-process' => 'in-process', 'waiting for documents' => 'waiting for documents', 'waiting for decision' => 'waiting for decision', 'cf approved' => 'cf approved', 'approved' => 'approved', 'disbursement checklist done' => 'disbursement checklist done', 'disbursement query' => 'disbursement query', 'query resolved' => 'query resolved', 'ready for disbursement' => 'ready for disbursement', 'disbursed' => 'disbursed', 'cancellation in-process' => 'cancellation in-process', 'cancelled' => 'cancelled', 'nach registered' => 'nach registered', 'closed' => 'closed', 'rejected' => 'rejected', 'aborted' => 'aborted', 'pre approved' => 'pre approved', 'settlement-in-progress' => 'settlement-in-progress', 'settlement-done' => 'settlement-done', 'settlement-aborted' => 'settlement-aborted', 'settled' => 'settled'];

        $this->statusarray = array('incomplete form' => array('form completed', 'rejected', 'aborted'), 'form completed' => array('in-process', 'rejected', 'aborted'), 'in-process' => array('waiting for documents', 'waiting for decision', 'rejected', 'aborted'), 'waiting for documents' => array('waiting for decision', 'in-process', 'rejected', 'aborted'), 'waiting for decision' => array('waiting for documents', 'in-process', 'rejected', 'aborted', 'pre approved', 'cf approved'), 'pre approved' => array('waiting for documents', 'in-process', 'rejected', 'aborted'), 'cf approved' => array('disbursement checklist done', 'rejected', 'aborted'), 'approved' => array('disbursement checklist done', 'rejected', 'aborted', 'cf approved'), 'disbursement checklist done' => array('approved', 'rejected', 'aborted'), 'disbursement query' => array('query resolved', 'aborted'), 'ready for disbursement' => array('disbursement checklist done', 'rejected', 'aborted'), 'disbursed' => array('nach registered', 'closed', 'cancellation in-process', 'settlement-in-progress'), 'nach registered' => array('closed', 'cancellation in-process', 'disbursed', 'settlement-in-progress'), 'closed' => array(), 'cancellation in-process' => array('cancelled'), 'cancelled' => array(), 'rejected' => array('in-process'), 'aborted' => array('in-process'));
        
        $this->secondaryStatusArray = array('settlement-in-progress' => array('settlement-done', 'settlement-aborted'), 'settlement-aborted' => array('settlement-in-progress'), 'settlement-done' => array('settled'));

        $this->arraygroup = array('incomplete form' => 'form completed', 'form completed' => 'form completed', 'in-process' => 'in-process', 'waiting for documents' => 'in-process', 'waiting for decision' => 'in-process', 'pre approved' => 'pre approved' ,'cf approved' => 'approved', 'approved' => 'approved', 'disbursement checklist done' => 'approved', 'disbursement query' => 'approved', 'ready for disbursement' => 'approved', 'disbursed' => 'disbursed', 'nach registered' => 'nach registered', 'closed' => 'closed', 'cancellation in-process' => 'cancelled', 'cancelled' => 'cancelled', 'rejected' => 'rejected', 'aborted' => 'aborted');

        $this->helptext = array('incomplete form' => 'Form Completed ->In Process', 'form completed' => 'In Process', 'in-process' => 'Gather Documents ->Complete Verification Checklist', 'waiting for documents' => 'Gather Documents -> Complete Verification Checklist', 'waiting for decision' => 'Get Decision From Credit Team', 'approved' => 'Get Agreement Signed ->Get Nach Registered ->Pro-Forma ->disbursement checklist done', 'disbursement checklist done' => 'Get Disbursement Approval', 'ready for disbursement' => 'Get Disbursed', 'disbursed' => 'Get Nach Activated', 'nach registered' => 'Keep a track of EMI', 'closed' => 'Keep it touch for more services', 'rejected' => 'Return to In process?', 'aborted' => 'Return to In process?', 'cancelled' => 'Refunded or Cancelled by Merchant', 'cancellation in-process' => "Co-ordinate with merchant for cancellation", 'pre approved' => 'Gather Documents ->Complete Verification Checklist->Approve');

        $this->pendingDoc = array('in-process' => ['Bureau' => 'equifax_report', 'Pan' => 'pan_card', 'Pan Valid' => 'panvalidation', 'Add' => 'address', 'Tenure' => 'foir', 'Co-applicant Income' => 'co_applicant_for_income', 'Co-applicant Sign' => 'co_applicant_for_signing'], 'waiting for documents' => ['Bureau' => 'equifax_report', 'Pan' => 'pan_card', 'Pan Valid' => 'panvalidation', 'Add' => 'address', 'Tenure' => 'foir', 'Co-applicant Income' => 'co_applicant_for_income', 'Co-applicant Sign' => 'co_applicant_for_signing'], 'approved' => ['Bank Valid' => 'bank_details', 'Sign Proforma' => 'proforma', 'Nach' => 'nach', 'Chq' => 'security_cheques', 'E-Sign' => 'agreement', 'Pan Card' => 'pan_card'], 'disbursed' => ['courier' => 'courier', 'Reg Nach' => 'reg_nach'], 'waiting for decision' => ['pending decision' => 'pending_decision']);

        $this->statusreversearray = array('incomplete form' => array(''), 'form completed' => array('incomplete form'), 'in-process' => array('form completed', 'incomplete form', 'rejected', 'aborted'), 'waiting for documents' => array('form completed', 'incomplete form', 'rejected', 'aborted', 'in-process'), 'waiting for decision' => array('form completed', 'incomplete form', 'rejected', 'aborted', 'in-process', 'waiting for documents'), 'cf approved' => array('form completed', 'incomplete form', 'rejected', 'aborted', 'in-process', 'waiting for documents', 'waiting for decision', 'pre approved'), 'approved' => array('form completed', 'incomplete form', 'rejected', 'aborted', 'in-process', 'waiting for documents', 'waiting for decision', 'pre approved','cf approved'), 'pre approved' => array('form completed', 'incomplete form', 'rejected', 'aborted', 'in-process', 'waiting for documents', 'waiting for decision'), 'disbursement checklist done' => array('form completed', 'incomplete form', 'rejected', 'aborted', 'in-process', 'waiting for documents', 'waiting for decision', 'approved', 'pre approved', 'disbursement query'), 'disbursement query' => array('form completed', 'incomplete form', 'rejected', 'aborted', 'in-process', 'waiting for documents', 'waiting for decision', 'approved', 'pre approved', 'disbursement checklist done'),  'query resolved' => array('form completed', 'incomplete form', 'rejected', 'aborted', 'in-process', 'waiting for documents', 'waiting for decision', 'approved', 'pre approved', 'disbursement checklist done'), 'ready for disbursement' => array('form completed', 'incomplete form', 'rejected', 'aborted', 'in-process', 'waiting for documents', 'waiting for decision', 'approved', 'disbursement checklist done', 'disbursement query', 'pre approved'), 'disbursed' => array('form completed', 'incomplete form', 'rejected', 'aborted', 'in-process', 'waiting for documents', 'waiting for decision', 'approved', 'disbursement checklist done', 'disbursement query', 'ready for disbursement', 'cancelled', 'cancellation in-process', 'pre approved'), 'nach registered' => array('form completed', 'incomplete form', 'rejected', 'aborted', 'in-process', 'waiting for documents', 'waiting for decision', 'approved', 'disbursement checklist done', 'disbursement query', 'ready for disbursement', 'disbursed', 'cancelled', 'cancellation in-process', 'pre approved'), 'closed' => array('form completed', 'incomplete form', 'rejected', 'aborted', 'in-process', 'waiting for documents', 'waiting for decision', 'approved', 'disbursement checklist done', 'disbursement query', 'ready for disbursement', 'disbursed', 'nach registered', 'cancelled', 'cancellation in-process', 'pre approved'), 'rejected' => array('form completed', 'incomplete form', 'rejected', 'aborted', 'in-process', 'waiting for documents', 'waiting for decision', 'approved', 'disbursement checklist done', 'disbursement query', 'ready for disbursement', 'cancelled', 'cancellation in-process', 'pre approved'), 'aborted' => array('form completed', 'incomplete form', 'rejected', 'aborted', 'in-process', 'waiting for documents', 'waiting for decision', 'approved', 'disbursement checklist done', 'disbursement query', 'ready for disbursement', 'cancelled', 'cancellation in-process'), 'cancelled' => array('form completed', 'incomplete form', 'rejected', 'aborted', 'in-process', 'waiting for documents', 'waiting for decision', 'approved', 'disbursement checklist done', 'disbursement query', 'ready for disbursement', 'disbursed', 'nach registered', 'cancelled', 'closed', 'cancellation in-process', 'pre approved'), 'cancellation in-process' => array('form completed', 'incomplete form', 'rejected', 'aborted', 'in-process', 'waiting for documents', 'waiting for decision', 'approved', 'disbursement checklist done', 'disbursement query', 'ready for disbursement', 'disbursed', 'nach registered', 'closed', 'cancellation in-process', 'pre approved'));

        $this->DocsStatus = ['waiting for decision' => ['equifax_report', 'pan_card', 'panvalidation', 'address', 'foir'], 'approved' => ['approved_amount'], 'disbursement checklist done' => ['pan_card','generate_emi', 'sanction_letter', 'pro_forma_invoice', 'agreement', 'nach', 'proforma', 'bank_details', 'security_cheques','insurance_payment_receipt','advance_amount_receipt','solar_installation_proof']];

        $this->otherWebhookEvents = ['utr', 'ntc', 'Merchant-Comment', 'Add-Co-applicant', 'Paytm-Webhook', 'VKYC-Webhook', 'Loan-Agreement-Signing-Webhook', 'NACH-Webhook', 'DA-Confirmation-Webhook', 'JSON-BRE', 'Pre-eligibility', 'Document-Verification-Webhook', 'Mandatory-Document-Webhook', 'table-of-offers-webhook'];

        $this->statusBeforeApproved = ['incomplete form','form completed','in-process','waiting for documents'];

        $this->statusBeforeDCD = ['incomplete form','form completed','in-process','waiting for decision','waiting for documents','pre approved','cf approved','approved'];

        $this->releaseDates = ["insurance_new_calculation" => "2025-02-20", "aadhar_mobile_check" => "2025-01-29", "aadhar_mobile_check_v2" => "2025-07-01", "insurance_gross_calculation" => "2026-07-23"];

        $this->solar_category = ["atta_chakki" => 2];

        $this->blackSoilApplications = [179021,179341,182328,182521,191453,198086,200791,201680,201910,202048,202388,203133,203945,204268,205431,205779,206055,206675,207579,209134,210904,212813,213019,213177,213456,215676,215959,218188,220366,220998,221597,221867,222828,222988,222994,223103,223244,223317,223420,225133,225463,225855,225906,227489,227806,227853,227961,228048,228756,229103,229111,229226,229268,229697,229997,230093,230163,230239,230415,230604,231087,231228,231269,231307,231430,231555,231952,232153,232319,232432,232980,233295,233382,233414,233661,233803,233874,234163,234197,234676,234972,235283,235310,235404,235496,235543,235611,235647,235704,235805,235812,235926,236055,236156,237057,237272,237303,237386,237883,237938,238319,238467,238607,238850,239060,239117,239394,239688,240083,240251,240310,240569,240675,240793,240896,240898,241195,241385,241412,241481,241645,241704,241795,241826,241954,241964,242097,242099,242103,242154,242227,242971,243167,243194,243200,243211,243330,243971,244074,244120,244218,244346,244483,244519,244800,244811,244874,244885,245044,245195,245499,245514,245670,245687,245800,246036,246385,246441,246718,246861,247188,247234,247393,247582,247590,247640,247783,247794,247821,247972,247998,248271,248443,248467,248654,248696,248740,248926,248969,249037,249043,249124,249126,249232,249315,249399,249498,249553,249802,249949,249977,249990,250059,250086,250107,250153,250162,250216,250526,250552,250630,250648,250732,250919,251226,251278,251282,251387,251563,251604,251714,251913,252047,252223,252628,252832,252858,252940,253129,253155,253168,253409,253462,253511,253601,253760,253768,253794,253910,253975,254220,254258,254295,254490,254972,255010,255034,255106,255107,255128,255215,255291,255293,255294,255412,255505,255748,255825,255826,255980,256013,256058,256211,256321,256462,256498,256711,256805,256857,256878,257016,257038,257113,257249,257466,257472,257503,257599,257617,258007,258028,258081,258239,258314,258336,258398,258602,258610,258655,258727,258771,258823,258986,259006,259072,259133,259280,259564,259821,259840,259866,259917,260091,260169,260195,260214,260311,260423,260508,260557,260567,260592,260602,260612,260681,260696,260733,260797,260803,260804,261115,261237,261482,261511,261579,261731,261734,261736,261772,261897,262063,262185,262224,262262,262286,262328,262399,262447,262465,262579,262591,262639,262649,262679,262716,262899,262901,262915,262957,263219,263342,263390,263391,263483,263595,263764,263880,263926,264265,264325,264360,264460,264551,264576,264769,264918,265023,265117,265201,265423,265680,265729,265857,265874,266021,266031,266066,266112,266123,266195,266280,266281,266332,266478,266609,266728,266996,267018,267099,267161,267252,267381,267544,267555,267788,267934,267965,268052,268100,268278,268279,268291,268320,268402,268583,268651,268680,268694,268721,268724,268810,268883,269006,269038,269295,269312,269372,269534,269677,269743,269758,269773,269788,269960,269968,269996,270101,270174,270189,270193,270212,270220,270225,270282,270315,270330,270369,270396,270452,270487,270507,270603,270744,270753,270882,270895,270935,270971,270977,271037,271052,271214,271281,271289,271299,271315,271370,271443,271509,271529,271557,271589,271656,271673,271679,271713,271719,271807,271817,271826,272059,272078,272103,272113,272131,272159,272196,272207,272337,272388,272411,272476,272479,272492,272627,272639,272677,272731,272759,272838,272874,272954,273025,273058,273130,273219,273240,273396,273408,273450,273569,273791,273867,273934,273941,273943,273946,274077,274195,274207,274253,274347,274362,274364,274417,274463,274556,274607,274702,274787,274804,274840,275024,275077,275153,275181,275221,275366,275534,275571,275600,275602,275681,275768,275809,275910,275948,276013,276018,276193,276200,276285,276287,276319,276405,276442,276450,276476,276602,276678,276679,276698,276754,276812,276833,276965,276987,277078,277200,277201,277266,277382,277394,277442,277454,277503,277511,277580,277589,277617,277622,277624,277629,277683,277743,277758,277767,277769,277884,277919,277938,277981,277991,277992,278091,278253,278310,278690,278704,278720,278787,278826,279260,279384,279772];

    }
    public function homepage(Request $request){
        return view('admin.homepage', $this->getFilters($request));
    }

    public function index(Request $request)
    {
        $dashboard_filter = ($request->has('filter') && !empty($request->get('filter'))) ? $request->get('filter') : "";
        if ($dashboard_filter != "") {
            $dashboard_filter_array = json_decode(base64_decode($dashboard_filter));
        }
        $keyword = $request->input('search_text');
        $search_text_by = $request->input('search_text_by');
        $default_search_text_by = 'id';
        // if (!$search_text_by){
        //     $keyword = '';
        // }
        $data['status'] = $request->has('status') ? $request->get('status') : '';
        $isNewFiveApplicationFilter = false;
        if ($data['status'] == 'new merchant'){
            $data['status'] = '';
            $isNewFiveApplicationFilter = true;
        }

        $data['from_date'] = ($request->has('from_date') && !empty($request->get('from_date'))) ? Carbon::createFromFormat('Y-m-d', $request->get('from_date'))->toDateString() : '';
        $data['to_date'] = ($request->has('to_date') && !empty($request->get('to_date'))) ? Carbon::createFromFormat('Y-m-d', $request->get('to_date'))->toDateString() : '';
        $selected_categories = explode(',', Auth::user()->category);

        $data['search_text'] = $keyword;
        $data['search_text_by'] = $search_text_by;
        $data['merchant_id'] = ($request->has('merchant_id')) ? $request->get('merchant_id') : '';
        $data['_merchant_id'] = ($request->has('_merchant_id')) ? $request->get('_merchant_id') : '';
        $data['merchant_category_id'] = ($request->has('merchant_category_id')) ? $request->get('merchant_category_id') : '';
        $data['center_id'] = ($request->has('center_id')) ? $request->get('center_id') : '';
        $data['user_id'] = ($request->has('user_id')) ? $request->get('user_id') : '';
        $data['lender_id'] = ($request->has('lender_id')) ? $request->get('lender_id') : '';
        $data['_application_status'] = ($request->has('_application_status')) ? $request->get('_application_status') : '';
        $data['_application_secondary_status'] = ($request->has('_application_secondary_status')) ? $request->get('_application_secondary_status') : '';
        $data['sort_field'] = ($request->has('sort_field')) ? $request->get('sort_field') : 'updated_at';
        $data['sort_direction'] = ($request->has('sort_direction')) ? $request->get('sort_direction') : 'desc';
        $data['merchant_sub_category_id'] = ($request->has('merchant_sub_category_id')) ? $request->get('merchant_sub_category_id') : null;
        // search code end


        $data['sidebar'] = 'consumer-applications';

        /*if($keyword){
            $applicationKeyword = new ConsumerApplication();
            if($search_text_by == 'name'){
                $applicationKeyword = $applicationKeyword->where('name', 'like', '%' . $keyword . '%');
            }else if($search_text_by == 'email'){
                $applicationKeyword = $applicationKeyword->where('email', 'like', '%' . $keyword . '%');
            }else if($search_text_by == 'id'){
                $applicationKeyword = $applicationKeyword->where('id', $keyword);
            }else if($search_text_by == 'co_applicant_name'){
                $applicationKeyword = $applicationKeyword->where('co_applicant_name', 'like', '%' . $keyword . '%');
            }else if($search_text_by == 'co_applicant_email'){
                $applicationKeyword = $applicationKeyword->where('co_applicant_email', 'like', '%' . $keyword . '%');
            }else if($search_text_by == 'co_applicant_mobile_number'){
                $applicationKeyword = $applicationKeyword->where('co_applicant_mobile_number', 'like', '%' . $keyword . '%');
            }else if($search_text_by == 'mobile_number'){
                $applicationKeyword = $applicationKeyword->where('mobile_number', 'like', '%' . $keyword . '%');
            }else if($search_text_by == 'alt_contact_number'){
                $applicationKeyword = $applicationKeyword->where('alt_contact_number', 'like', '%' . $keyword . '%');
            }else if($search_text_by == 'pan_card'){
                $applicationKeyword = $applicationKeyword->where(function ($query) use ($keyword) {
                    $query->where('pan_card', 'like', '%' . $keyword . '%')
                        ->orWhere('pan_card', 'like', '%' . strtoupper($keyword) . '%')
                        ->orWhere('pan_card', 'like', '%' . strtolower($keyword) . '%');
                });
            }else if($search_text_by == 'co_applicant_pan_card'){
                $applicationKeyword = $applicationKeyword->where(function ($query) use ($keyword) {
                    $query->where('co_applicant_pan_card', 'like', '%' . $keyword . '%')
                        ->orWhere('co_applicant_pan_card', 'like', '%' . strtoupper($keyword) . '%')
                        ->orWhere('co_applicant_pan_card', 'like', '%' . strtolower($keyword) . '%');
                });
            }

            $applicationKeyword = $applicationKeyword->whereNull('is_deleted')->get(['id']);

            $filterIds = [];
            foreach($applicationKeyword as $item){
                $filterIds[] = $item->id;
            }
        }*/

        ConsumerApplication::isApplicantType(true);
        $applicationData = \App\ConsumerApplication::with('application_element','disbursement_requests', 'PayoutStatus', 'CFPayoutDirectTransfer','checkmandate', 'offer.disbursementOffer', 'documents', 'logs', 'digital_sign', 'merchant', 'merchant.anchorMerchant', 'merchant.merchant_category', 'category', 'emi', 'creditReport', 'application_element.merchant_center', 'advisor', 'comments.user', 'bank_details','finBitData', 'cibilReportBorrower' ,'cibilReportCoBorrower','AvanseNoc','agency','digioLoanAgreement','disbursementOfferDisbursed','lender', 'application_element.vendor', 'electricity_bill', 'logger', 'proFormaInvoice');
        if($keyword || $search_text_by) {
            if ($search_text_by == 'name') {
                //$applicationData = $applicationData->where('name' ,'like', '%'.$keyword.'%');
                //$applicationData = $applicationData->where(DB::raw('LOWER(TRIM(name))'), 'LIKE', '%' . strtolower($keyword) . '%');
                $applicationData = $applicationData->where(DB::raw("REGEXP_REPLACE(name, ' {2,}', ' ')"), 'LIKE', '%' . strtolower($keyword) . '%');



            }else if ($search_text_by == 'lan_id') {
                $app_id = AvanseCreateFinance::getAvanseCustomerId($keyword);
                $applicationData = $applicationData->where('id', $app_id);
            }else if ($search_text_by == 'email') {
                $applicationData = $applicationData->where('email', $keyword);
            } else if ($search_text_by == 'id' || empty($search_text_by)) {
                $applicationData = $applicationData->where('id', $keyword);
            } else if ($search_text_by == 'co_applicant_name') {
                $applicationData = $applicationData->where('co_applicant_name' ,'like', '%'.$keyword.'%');
            } else if ($search_text_by == 'co_applicant_email') {
                $applicationData = $applicationData->where('co_applicant_email', $keyword);
            } else if ($search_text_by == 'co_applicant_mobile_number') {
                $applicationData = $applicationData->where('co_applicant_mobile_number', $keyword);
            } else if ($search_text_by == 'mobile_number') {
                $applicationData = $applicationData->where('mobile_number', $keyword);
            } else if ($search_text_by == 'aadhaar_card') {
                $applicationData = $applicationData->where('aadhaar_card', $keyword);
            } else if ($search_text_by == 'co_applicant_aadhaar_card') {
                $applicationData = $applicationData->where('co_applicant_aadhaar_card', $keyword);
            } else if ($search_text_by == 'transaction_id') {
                $paymentData = PaymentTransaction::where('trasanction_id', $keyword)->groupBy('application_id')->get(['application_id']);
                if ($paymentData && isset($paymentData[0]) && isset($paymentData[0]->application_id)) {
                    $ids_payment = [];
                    foreach ($paymentData as $_payment_item){
                        $ids_payment[] = $_payment_item->application_id;
                    }
                    if($ids_payment) {
                        $applicationData = $applicationData->whereIn('id', $ids_payment);
                    }
                }
            }  else if ($search_text_by == 'alt_contact_number') {
                $applicationData = $applicationData->where('alt_contact_number', $keyword);
            } else if ($search_text_by == 'pan_card') {
                $applicationData = $applicationData->where(function ($query) use ($keyword) {
                    $query->where('pan_card', $keyword)
                        ->orWhere('pan_card',strtoupper($keyword))
                        ->orWhere('pan_card', strtolower($keyword));
                });
            } else if ($search_text_by == 'co_applicant_pan_card') {
                $applicationData = $applicationData->where(function ($query) use ($keyword) {
                    $query->where('co_applicant_pan_card', $keyword)
                        ->orWhere('co_applicant_pan_card',strtoupper($keyword))
                        ->orWhere('co_applicant_pan_card',strtolower($keyword));
                });
            }
        }

        if(count(array_filter($selected_categories))){
            $applicationData = $applicationData->whereIn('purpose',$selected_categories);
        }

        if ($request->has('first_emi_date') && $request->get('first_emi_date')) {
            $applicationData->whereHas('emi', function ($query) use ($request) {
                $query->where('emi_date', date('Y-m-d', strtotime($request->get('first_emi_date'))));
            });
        }

        /*if(isset($filterIds)){
            $applicationData->whereIn('id', $filterIds);
        }*/

        if ($request->has('nach_status') && $request->get('nach_status')) {
            $applicationData->whereHas('mandateMany', function ($query) use ($request) {
                $query->where('status', $request->get('nach_status'));
            });
        }

        if (($request->has('risky_merchant') && $request->get('risky_merchant') != "false") || ($request->has('vulnerable_merchant') && $request->get('vulnerable_merchant') != "false")) {
            $applicationData->whereHas('merchant', function ($query) use ($request) {
                if ($request->has('risky_merchant') && $request->get('risky_merchant') != "false")
                    $query->where('high_risk', 1);
                if ($request->has('vulnerable_merchant') && $request->get('vulnerable_merchant') != "false")
                    $query->where('vulnerable_merchant', 1);
            });
        }

        if ($request->has('multi_tranche') && $request->get('multi_tranche') != "false") {
            $disb_log_id = [];
            $applicationData->whereHas('disbursement_log', function ($query){

                $disb_log_arr = DB::select(DB::raw('select count(application_id),application_id from disbursement_log 
                group by application_id having count(application_id) < 2'));
                if(!empty($disb_log_arr)){
                    foreach($disb_log_arr as $v){
                        if(!empty($v->application_id)){
                            $disb_log_id[] = $v->application_id;
                        }
                    }
                }
                if (isset($disb_log_id) && count($disb_log_id) > 0) {
                    $query->whereIn('application_id', $disb_log_id);
                }
            });
        }

        if ($request->has('multi_tranche_requested') && $request->get('multi_tranche_requested') != "false") {

            $disb_log_id = [];

            $applicationData->whereHas('disbursement_requests', function ($query){
                $disb_log_arr = DB::select(DB::raw('select count(application_id),application_id from next_phase_disbursement_requests group by application_id'));
                if(!empty($disb_log_arr)){
                    foreach($disb_log_arr as $v){
                        if(!empty($v->application_id)){
                            $disb_log_id[] = $v->application_id;
                        }
                    }
                }
                if (isset($disb_log_id) && count($disb_log_id) > 0) {
                    $query->whereIn('application_id', $disb_log_id);
                }
                $query->orderBy('created_at','desc');
            });
        }

        if ($request->has('nach_mode') && $request->get('nach_mode')) {
            $applicationData->whereHas('mandateMany', function ($query) use ($request) {
                if ($request->get('nach_mode') == 'lotuspay') {
                    $query->whereIn('mode', ['lotuspay', 'lotuspay_emandate', 'lotuspay_physical']);
                } else if (in_array($request->get('nach_mode'), ['hdfc_nach', 'rbl_nach'])) {
                    $query->where('mode', 'nach');
                }
            });
        }

        if (in_array($request->get('nach_mode'), ['hdfc_nach', 'rbl_nach'])) {
            if ($request->get('nach_mode') == 'hdfc_nach') {
                $applicationData->where('lender_id', 2);
            } else {
                $applicationData->where('lender_id', 1);
            }
        }

        if(Auth::check() && Auth::user()->lender_id){
            if (Auth::user()->lender_id == 2) {
                $applicationData->whereHas('avanse_access')->whereNotIn('state', $this->statusreversearray['waiting for decision']);
            } else {
                $applicationData->where('lender_id', Auth::user()->lender_id)->whereNotIn('state', $this->statusreversearray['waiting for decision']);
            }
        }
        if(($request->has('application_type') && $request->get('application_type') == 'bnpl') || strpos($request->path(),'bnpl-application')) {
            $applicationData->whereHas('application_element', function ($query) {
                $query->where('is_bnpl', 1);
            });
        }else{
            $applicationData->whereHas('application_element', function ($query) {
                $query->where('is_bnpl', 0)->orWhereNull('is_bnpl');
            });
        }

        if ($request->get('source') == 'app' || $request->get('source') == 'website') {
            if($request->has('src_exclude_in') && $request->get('src_exclude_in') == 1){
                $applicationData->whereNotIn('updated_by', ['app','website']);
            }else{
                $applicationData->whereIn('updated_by', ['app','website']);
            }
        } elseif($request->get('source')) {
            if($request->has('src_exclude_in') && $request->get('src_exclude_in') == 1){
                $applicationData->where('updated_by', '!=',$request->get('source'));
            }else{
                $applicationData->where('updated_by', $request->get('source'));
            }
        }

        if ($request->has('tagged_in_comment') && $request->get('tagged_in_comment')) {
            $applicationData->whereHas('comments', function ($query) use ($request) {
                $query->where('comment', 'like', '%' . $request->get('tagged_in_comment') . '%');
            });
        }

        if ($data['from_date'] && $data['to_date']) {
            //$application->whereBetween('creted_at', array( $data['from_date']." 00:00:00", $data['to_date']." 23:59:59"));
            $applicationData->where('consumer_application.created_at', '>=', $data['from_date'] . " 00:00:00")->where('consumer_application.created_at', '<=', $data['to_date'] . " 23:59:59");
        } elseif ($data['to_date'] != '') {
            $applicationData->where('consumer_application.created_at', '>=', $data['from_date']);
        } elseif ($data['from_date'] != '') {
            $applicationData->where('consumer_application.created_at', '<=', $data['to_date']);
        }
        $statusarray = array();
        foreach ($this->arraygroup as $key => $arraygroup) {
            if ($arraygroup == $data['status']) {
                array_push($statusarray, $key);
            }
        }
        if ($data['status']) {
            $applicationData->wherein('state', $statusarray);
        }

        if ($request->has('merchant_id') && $request->get('merchant_id') > 0) {
            if($request->has('mr_exclude_in') && $request->get('mr_exclude_in') == 1){
                $applicationData->where('merchant_id', '!=',$request->get('merchant_id'));
            }else{
                $applicationData->where('merchant_id', $request->get('merchant_id'));
            }
        }
        if ($request->has('_merchant_id') && $request->get('_merchant_id') > 0) {
            if($request->has('mr_exclude_in') && $request->get('mr_exclude_in') == 1){
                $applicationData->whereNotIn('merchant_id',$request->get('_merchant_id'));
            }else{
                $applicationData->wherein('merchant_id', $request->get('_merchant_id'));
            }
        }
        if ($request->has('merchant_category_id') && $request->get('merchant_category_id') > 0) {
            $applicationData->whereHas('merchant', function ($query) use ($data) {
                $query->where('category_id', $data['merchant_category_id']);
            });
        }
        if (!Session::has('Show_PSU_Loans|-75')) {
            $applicationData->whereHas('merchant', function ($query) use ($data) {
                $query->whereNotIn('status', ['bre']);
            });
        }
        if ($request->has('merchant_sub_category_id') && $request->get('merchant_sub_category_id') > 0) {
            $applicationData->whereHas('application_element', function ($query) use ($data) {
                $query->whereIn('type_of_customer', $data['merchant_sub_category_id']);
            });
        }
        if ($request->has('lender_id') && $request->get('lender_id') > 0) {
            $applicationData->where('lender_id', $request->get('lender_id'));
        }
        if ($request->has('user_id') && $request->get('user_id') > 0) {
            $applicationData->where('created_by', $request->get('user_id'));
        }
        if ($data['_application_status']) {
            $applicationData->whereIn('state', $data['_application_status']);
        }
        if ($data['_application_secondary_status']) {
            $applicationData->whereIn('secondary_status', $data['_application_secondary_status']);
        }
        if ($data['center_id'] > 0) {
            $applicationData->whereHas('application_element', function ($query) use ($data) {
                $query->where('center_id', $data['center_id']);
            });
        }

        if (isset($data['merchant_id']) && $data['merchant_id'] > 0) {
            $data['centers'] = MerchantLocation::where('merchant_id', $data['merchant_id'])
                ->get();
        }
        if ($request->has('_merchant_id') && count($request->get('_merchant_id')) > 0) {
            $data['centers'] = MerchantLocation::whereIn('merchant_id', $data['_merchant_id'])
                ->get();
        }

        $visible_stages = $this->getStatusVisibilityPermissions();
        if(is_array($visible_stages) && count($visible_stages) > 0) {
            $applicationData->whereIn('state', $visible_stages);
        }

        if (isset($dashboard_filter_array[0])) {
            $applicationData->whereIn('id', $dashboard_filter_array);
        }

        //FiveApplicationFilter
        /*if($isNewFiveApplicationFilter){
            $isNewFiveApplicationFilterData = ConsumerApplication::whereNull('is_deleted')->groupBy('merchant_id')->having(DB::raw('count(merchant_id)'), '<=', 5)->having(DB::raw('count(merchant_id)'), '>', 0)->get(['merchant_id', DB::raw('count(merchant_id) as app_received')]);
            $isNewFiveApplicationFilterDataMerchant = [];
            foreach ($isNewFiveApplicationFilterData as $isNewFiveApplicationFilterDataItem) {
                if ($isNewFiveApplicationFilterDataItem->app_received == 5) {
                    $hasCount = ConsumerApplication::where('merchant_id', $isNewFiveApplicationFilterDataItem->merchant_id)->whereIn('state', $this->statusreversearray['approved'])->whereNull('is_deleted')->get(['id']);
                    if (count($hasCount)) {
                        $isNewFiveApplicationFilterDataMerchant[] = $isNewFiveApplicationFilterDataItem->merchant_id;
                    }
                } else {
                    $isNewFiveApplicationFilterDataMerchant[] = $isNewFiveApplicationFilterDataItem->merchant_id;
                }
            }

            $merchantItems = Merchant::whereIn('id',$isNewFiveApplicationFilterDataMerchant)->where('status','active')->where('is_guest_active', 1)->whereNull('deleted_at')->get(['id']);

            $applicationData->whereIn('merchant_id', $merchantItems)->whereIn('state', $this->statusreversearray['approved']);
        }*/

        //Advance Filters
        if ($request->has('min_amount') && $request->get('min_amount') > 0) {
            $applicationData->where('loan_amount', '>=', (int)$request->get('min_amount'));
        }
        if ($request->has('max_amount') && $request->get('max_amount') > 0) {
            $applicationData->where('loan_amount', '<=', (int)$request->get('max_amount'));
        }

        if ($request->has('min_tenure') && $request->get('min_tenure') > 0) {
            $applicationData->where('tenure', '>=', $request->get('min_tenure'));
        }
        if ($request->has('max_tenure') && $request->get('max_tenure') > 0) {
            $applicationData->where('tenure', '<=', $request->get('max_tenure'));
        }
        if ($request->has('cpv_pending') && $request->get('cpv_pending') != "false") {
            $applicationData->whereHas('emi', function ($query) {
                $query->havingRaw(DB::raw('consumer_application.approved_amount-upfront_from_customer > 250000'));
            });
        }
       //end of Advance Filters

        /*if ($request->has('courier_status') && $request->get('courier_status')) {

            if ($request->get('courier_status') != 'pending') {
                $applicationData = $applicationData->join('couriers as c', 'c.documents', 'like', DB::RAW("CONCAT('%\"document_for_id\":\"',consumer_application.id,'\"%')"))
                    ->where('documents', 'like', '%"document_for":"2"%');
                if ($request->get('courier_status') == 'cheq') {
                    $applicationData = $applicationData->where('documents', 'like', '%security_cheques%');
                }
                if ($request->get('courier_status') == 'nach') {
                    $applicationData = $applicationData->where('documents', 'like', '%nach%');
                }

                if ($request->get('courier_status') == 'cheq_nach') {
                    $applicationData = $applicationData->where('documents', 'like', '%nach%')->where('documents', 'like', '%security_cheques%');
                }
            } else {
                $applicationData = $applicationData->whereNotExists(function ($query) {
                    $query->select('*')
                        ->from('couriers')
                        ->where('couriers.documents', 'like', DB::RAW("CONCAT('%\"document_for_id\":\"',consumer_application.id,'\"%')"));
                });
            }
        }*/

        $filterData = $request->all();
        unset($filterData['_token']);
        if (!isset($filterData['search_text_by']) || (isset($filterData['search_text_by']) && !$filterData['search_text_by'])){
            unset($filterData['search_text']);
        }
        unset($filterData['search_text_by']);
        $filterData = array_filter(array_values($filterData));
        $count = count($filterData);

        if (Auth::user()->user_type == _env('BLACKSOIL_USER_TYPE')) {
            $this->blackSoilApplications = array_merge($this->blackSoilApplications, [65229,
70073,
71223,
72156,
75447,
76382,
77700,
82078,
86366,
88342,
89846,
89984,
90813,
91050,
92416,
92610,
93618,
94023,
96911,
98832,
98896,
99977,
100418,
100650,
101712,
104003,
104597,
105298,
105498,
106330,
106574,
107801,
109909,
110707,
110709,
115041,
117004,
117566,
119701,
120857,
120872,
121209,
121746,
122509,
124633,
125855,
126092,
126492,
126856,
126884,
127208,
128162,
128653,
128785,
128936,
129606,
131174,
131521,
132737,
132970,
133506,
133795,
133837,
133838,
134597,
134682,
135339,
135889,
138621,
142278,
142656,
145282,
147240,
150281,
150780,
152846,
153473,
153508,
154184,
154753,
155239,
156968,
157345,
158302,
163069,
166103,
166366,
166814,
167959,
168180,
171718,
172629,
172922,
173050,
173090,
173719,
173814,
174190,
174687,
175091,
176212,
177016,
177568,
177876,
177896,
178909,
179188,
179336,
179585,
179991,
180249,
180750,
182155,
182292,
182310,
182843,
183259,
183365,
184162,
184238,
184569,
185119,
185310,
185535,
185563,
185725,
186220,
186653,
186975,
187094,
187098,
187101,
187123,
187150,
187227,
187304,
188105,
188178,
188541,
188559,
188679,
188806,
188825,
189002,
189067,
189432,
189574,
189752,
190160,
190560,
190704,
190765,
190870,
191176,
191419,
191692,
191909,
191954,
192572,
193180,
193356,
193731,
193890,
194734,
194967,
195162,
195180,
195337,
195388,
195412,
195428,
195620,
195791,
195852,
195986,
196009,
196589,
196658,
196721,
197060,
197368,
197391,
197570,
197646,
197719,
197860,
198090,
198220,
198247,
198470,
198471,
198971,
199212,
199478,
199564,
199618,
199999,
200066,
200254,
200335,
200715,
201470,
201479,
201517,
201659,
201671,
201730,
201847,
202161,
202220,
202598,
202666,
202769,
203026,
203192,
203212,
203303,
203621,
203859,
204015,
204016,
204267,
204655,
204969,
204975,
204996,
205058,
205218,
205291,
205371,
205516,
205635,
205768,
205785,
206002,
206022,
206041,
206375,
206380,
206382,
206663,
207330,
207331,
207411,
207425,
207468,
207482,
207511,
207540,
207582,
207633,
207698,
207710,
207785,
207819,
208353,
208481,
209195,
210067,
210103,
210146,
210411,
210427,
210542,
211157,
211221,
211703,
211942,
211963,
211984,
212217,
212319,
212498,
212528,
212579,
212638,
212667,
212892,
213066,
213195,
213212,
213311,
213319,
213413,
213572,
213961,
214087,
214114,
214153,
214389,
214395,
214469,
214509,
214547,
214666,
214792,
214818,
214855,
214904,
215073,
215122,
215240,
215243,
215286,
215404,
215411,
215532,
215632,
215703,
215705,
215743,
215795,
215855,
215872,
215969,
216027,
216230,
216408,
216951,
217019,
217167,
217326,
217390,
217741,
217801,
217861,
217923,
217941,
218144,
218177,
218286,
218559,
218667,
218806,
218813,
218847,
218951,
219197,
219252,
219269,
219987,
220008,
220073,
220157,
220209,
220228,
220235,
220370,
220594,
220741,
220790,
220810,
220876,
220915,
220975,
221137,
221215,
221273,
221299,
221329,
221358,
221398,
221441,
221557,
221583,
221605,
221805,
221835,
221972,
222203,
222372,
222496,
222634,
222709,
222771,
222854,
222930,
223130,
223136,
223219,
223260,
223280,
223461,
223479,
223481,
223558,
223629,
223797,
223954,
224037,
224150,
224216,
224274,
224284,
224639,
224671,
224684,
224765,
224799,
225059,
225118,
225132,
225350,
225367,
225370,
225380,
225509,
225532,
225590,
225645,
225653,
225689,
225758,
225783,
225799,
225810,
225823,
225896,
225904,
225909,
225910,
226165,
226190,
226205,
226245,
226282,
226415,
226445,
226570,
226600,
226820,
226852,
226896,
226920,
227002,
227101,
227111,
227141,
227147,
227176,
227206,
227312,
227313,
227359,
227407,
227479,
227511,
227512,
227534,
227691,
227704,
227706,
227834,
227838,
227854,
227864,
227882,
227991,
227993,
228072,
228193,
228390,
228500,
228552,
228553,
228569,
228575,
228588,
228619,
228645,
228649,
228675,
228792,
228845,
228917,
228929,
228991,
229046,
229073,
229143,
229187,
229266,
229386,
229389,
229404,
229521,
229535,
229572,
229574,
229659,
229662,
229718,
229761,
229840,
229904,
229928,
230003,
230055,
230061,
230091,
230098,
230145,
230146,
230193,
230197,
230362,
230401,
230505,
230519,
230539,
230568,
230712,
230720,
230753,
230754,
230803,
230856,
230886,
230939,
230965,
231002,
231037,
231142,
231170,
231193,
231194,
231242,
231258,
231297,
231378,
231448,
231450,
231484,
231496,
231558,
231707,
231867,
231869,
231899,
231913,
231918,
232014,
232106,
232121,
232141,
232159,
232235,
232333,
232359,
232436,
232472,
232503,
232605,
232625,
232769,
232786,
232799,
232824,
232876,
232954,
233006,
233016,
233122,
233310,
233338,
233375,
233383,
233390,
233397,
233452,
233471,
233487,
233498,
233561,
233618,
233795,
233878,
233898,
233903,
233904,
233915,
233918,
233944,
234008,
234054,
234315,
234417,
234472,
234531,
234548,
234766,
234925,
234993,
235145,
235157,
235236,
235300,
235301,
235429,
235461,
235468,
235658,
235702,
235752,
235806,
235818,
235883,
235991,
236074,
236124,
236132,
236138,
236195,
236264,
236277,
236295,
236325,
236591,
236606,
236858,
236876,
236909,
236940,
236971,
237011,
237027,
237092,
237143,
237173,
237350,
237371,
237580,
237679,
237686,
237771,
237807,
237841,
238063,
238092,
238191,
238200,
238305,
238318,
238493,
238569,
238605,
238699,
238864,
239020,
239052,
239057,
239115,
239154,
239244,
239627,
239635,
239743,
239744,
239765,
239796,
239834,
239840,
239851,
239895,
239896,
239926,
240007,
240105,
240123,
240349,
240529,
240536,
240652,
240799,
240935,
240963,
241032,
241064,
241133,
241140,
241157,
241191,
241204,
241214,
241251,
241298,
241404,
241421,
241543,
241591,
241674,
241744,
241793,
241886,
241900,
241931,
241933,
241984,
242061,
242100,
242138,
242172,
242266,
242372,
242439,
242533,
242577,
242601,
242631,
242663,
242747,
242795,
242848,
242914,
242981,
243123,
243171,
243185,
243205,
243397,
243411,
243429,
243455,
243457,
243458,
243491,
243556,
243586,
243592,
243634,
243653,
243655,
243661,
243663,
243667,
243674,
243726,
243760,
243779,
243826,
243894,
243925,
243959,
243968,
244094,
244196,
244198,
244199,
244315,
244359,
244385,
244418,
244427,
244459,
244611,
244680,
244687,
244753,
244781,
244809,
244937,
244980,
245047,
245049,
245050,
245090,
245091,
245099,
245108,
245193,
245208,
245232,
245244,
245272,
245360,
245401,
245448,
245469,
245562,
245593,
245628,
245673,
245698,
245763,
245863,
245879,
245891,
245924,
245939,
245989,
245993,
246046,
246048,
246111,
246132,
246152,
246165,
246187,
246241,
246322,
246325,
246339,
246360,
246380,
246432,
246448,
246503,
246507,
246547,
246610,
246690,
246892,
246904,
246922,
246939,
246994,
247023,
247033,
247148,
247171,
247175,
247189,
247202,
247243,
247253,
247261,
247306,
247332,
247354,
247386,
247403,
247462,
247495,
247514,
247515,
247547,
247571,
247584,
247601,
247641,
247706,
247716,
247729,
247860,
247863,
247946,
248096,
248101,
248102,
248113,
248120,
248151,
248173,
248396,
248449,
248464,
248481,
248492,
248538,
248563,
248590,
248610,
248658,
248662,
248674,
248675,
248686,
248699,
248737,
248800,
248801,
248902,
248904,
248916,
248952,
248960,
249035,
249039,
249056,
249110,
249173,
249201,
249211,
249274,
249305,
249319,
249321,
249343,
249376,
249432,
249442,
249601,
249640,
249643,
249701,
249740,
249759,
249812,
249889,
249917,
250093,
250109,
250133,
250197,
250269,
250318,
250353,
250404,
250449,
250477,
250497,
250583,
250605,
250639,
250683,
250725,
250744,
250863,
250873,
250934,
250952,
251142,
251171,
251290,
251309,
251330,
251338,
251360,
251368,
251382,
251487,
251495,
251512,
251554,
251587,
251615,
251624,
251626,
251630,
251646,
251667,
251750,
251759,
251801,
251858,
251899,
251929,
251955,
251988,
252193,
252222,
252280,
252293,
252331,
252374,
252424,
252468,
252528,
252560,
252571,
252586,
252589,
252703,
252720,
252735,
252783,
252844,
252845,
252847,
252909,
252961,
253121,
253122,
253147,
253207,
253277,
253279,
253287,
253309,
253314,
253329,
253388,
253410,
253416,
253565,
253587,
253622,
253634,
253657,
253659,
253669,
253678,
253693,
253705,
253757,
253809,
253831,
253841,
253913,
254031,
254061,
254064,
254131,
254163,
254167,
254173,
254194,
254360,
254365,
254376,
254424,
254454,
254476,
254495,
254510,
254535,
254598,
254599,
254642,
254707,
254843,
254898,
255036,
255051,
255133,
255135,
255153,
255159,
255160,
255166,
255230,
255265,
255437,
255452,
255487,
255534,
255555,
255653,
255760,
255806,
255834,
255837,
255846,
255889,
255971,
256022,
256067,
256116,
256151,
256181,
256301,
256399,
256402,
256405,
256524,
256560,
256575,
256659,
256660,
256747,
256806,
256823,
256850,
256897,
256919,
256922,
256962,
256988,
256999,
257059,
257088,
257154,
257156,
257222,
257262,
257277,
257358,
257393,
257400,
257405,
257431,
257454,
257462,
257517,
257518,
257575,
257590,
257596,
257650,
257661,
257664,
257823,
257844,
257860,
257878,
257947,
258065,
258083,
258108,
258122,
258312,
258342,
258346,
258348,
258352,
258358,
258364,
258390,
258435,
258457,
258565,
258585,
258599,
258614,
258627,
258702,
258720,
258724,
258765,
258788,
258814,
258855,
258919,
258931,
258934,
259080,
259145,
259162,
259269,
259283,
259284,
259294,
259295,
259344,
259367,
259371,
259403,
259479,
259537,
259546,
259598,
259601,
259603,
259612,
259621,
259628,
259644,
259665,
259694,
259696,
259719,
259725,
259745,
259751,
259779,
259782,
259784,
259788,
259797,
259841,
259885,
259888,
259894,
259920,
259923,
259973,
259974,
259977,
260011,
260017,
260048,
260081,
260085,
260118,
260125,
260133,
260135,
260156,
260174,
260189,
260207,
260210,
260235,
260236,
260244,
260258,
260310,
260335,
260374,
260396,
260452,
260457,
260473,
260514,
260523,
260541,
260558,
260590,
260635,
260636,
260660,
260662,
260689,
260704,
260716,
260717,
260726,
260739,
260741,
260778,
260841,
260865,
260875,
260922,
260988,
261007,
261084,
261218,
261249,
261250,
261259,
261267,
261294,
261307,
261322,
261331,
261344,
261351,
261362,
261365,
261402,
261493,
261501,
261563,
261568,
261606,
261611,
261651,
261654,
261722,
261762,
261764,
261822,
261823,
261847,
261871,
261884,
261893,
261932,
261936,
261948,
261976,
261989,
262001,
262011,
262041,
262044,
262055,
262071,
262096,
262126,
262149,
262181,
262197,
262213,
262225,
262241,
262266,
262287,
262324,
262332,
262373,
262414,
262429,
262449,
262506,
262513,
262534,
262544,
262565,
262589,
262626,
262685,
262695,
262702,
262717,
262737,
262749,
262760,
262765,
262795,
262810,
262833,
262852,
262932,
262934,
262954,
262997,
263050,
263080,
263108,
263148,
263158,
263161,
263162,
263195,
263213,
263215,
263229,
263263,
263267,
263325,
263336,
263350,
263361,
263385,
263402,
263403,
263433,
263444,
263470,
263486,
263487,
263511,
263522,
263525,
263527,
263537,
263556,
263585,
263592,
263593,
263655,
263656,
263666,
263668,
263675,
263683,
263699,
263706,
263710,
263776,
263791,
263835,
263836,
263938,
263942,
263971,
263985,
264186,
264195,
264198,
264222,
264224,
264272,
264279,
264282,
264283,
264311,
264327,
264332,
264336,
264395,
264398,
264401,
264407,
264419,
264430,
264454,
264530,
264539,
264585,
264611,
264635,
264665,
264666,
264674,
264678,
264733,
264742,
264765,
264787,
264788,
264810,
264819,
264825,
264829,
264830,
264893,
264898,
264937,
264938,
264954,
264957,
264967,
264968,
265016,
265030,
265032,
265040,
265090,
265105,
265150,
265165,
265210,
265223,
265226,
265240,
265241,
265248,
265250,
265253,
265273,
265306,
265331,
265336,
265361,
265413,
265416,
265422,
265449,
265451,
265468,
265478,
265504,
265507,
265511,
265512,
265517,
265529,
265530,
265538,
265555,
265574,
265575,
265587,
265602,
265626,
265627,
265630,
265650,
265651,
265667,
265681,
265695,
265731,
265755,
265777,
265781,
265797,
265809,
265814,
265840,
265842,
265856,
265861,
265895,
265897,
265928,
265942,
265945,
265947,
265948,
265965,
265969,
265973,
265990,
266007,
266009,
266010,
266012,
266013,
266034,
266035,
266080,
266089,
266090,
266184,
266224,
266239,
266257,
266283,
266301,
266330,
266343,
266345,
266380,
266382,
266389,
266408,
266417,
266433,
266447,
266462,
266465,
266487,
266489,
266514,
266515,
266562,
266571,
266577,
266583,
266586,
266606,
266626,
266634,
266654,
266661,
266668,
266677,
266680,
266731,
266751,
266754,
266760,
266777,
266793,
266807,
266824,
266837,
266844,
266899,
266919,
266944,
266960,
266968,
266991,
266993,
267011,
267025,
267054,
267063,
267079,
267080,
267084,
267112,
267123,
267127,
267136,
267141,
267155,
267158,
267173,
267188,
267197,
267200,
267220,
267231,
267261,
267286,
267302,
267318,
267334,
267336,
267351,
267384,
267387,
267419,
267423,
267425,
267430,
267441,
267455,
267491,
267520,
267549,
267556,
267564,
267578,
267582,
267585,
267598,
267609,
267638,
267641,
267687,
267690,
267710,
267716,
267722,
267726,
267742,
267754,
267770,
267771,
267791,
267813,
267881,
267882,
267885,
267888,
267938,
267947,
268018,
268105,
268129,
268151,
268160,
268199,
268200,
268204,
268206,
268212,
268213,
268222,
268237,
268270,
268277,
268281,
268285,
268299,
268308,
268315,
268347,
268387,
268436,
268505,
268531,
268542,
268545,
268554,
268555,
268558,
268567,
268621,
268624,
268648,
268658,
268660,
268663,
268683,
268739,
268805,
268809,
268853,
268863,
268915,
268933,
268949,
268970,
268975,
268985,
269003,
269040,
269083,
269084,
269097,
269102,
269144,
269149,
269173,
269186,
269190,
269196,
269208,
269230,
269231,
269232,
269245,
269259,
269273,
269296,
269305,
269311,
269313,
269317,
269319,
269329,
269349,
269355,
269360,
269371,
269394,
269410,
269419,
269440,
269448,
269510,
269528,
269551,
269552,
269569,
269571,
269591,
269600,
269615,
269619,
269642,
269701,
269746,
269760,
269762,
269763,
269764,
269768,
269771,
269792,
269794,
269796,
269799,
269803,
269818,
269829,
269850,
269854,
269869,
269883,
269899,
269920,
269924,
269932,
269946,
269949,
269950,
269952,
269957,
269962,
269965,
269974,
269990,
270016,
270027,
270061,
270084,
270092,
270102,
270108,
270113,
270137,
270150,
270176,
270210,
270234,
270251,
270252,
270265,
270272,
270279,
270281,
270311,
270314,
270325,
270326,
270333,
270346,
270363,
270383,
270388,
270412,
270458,
270513,
270522,
270526,
270535,
270540,
270544,
270557,
270558,
270578,
270592,
270632,
270638,
270644,
270655,
270661,
270684,
270714,
270720,
270722,
270725,
270739,
270746,
270751,
270760,
270764,
270771,
270807,
270824,
270826,
270872,
270876,
270893,
270894,
270901,
270925,
270926,
270934,
270936,
270941,
270943,
270957,
270966,
270983,
270997,
270998,
271017,
271042,
271059,
271094,
271190,
271195,
271216,
271222,
271226,
271235,
271250,
271258,
271261,
271278,
271290,
271303,
271327,
271362,
271371,
271394,
271403,
271409,
271412,
271420,
271436,
271447,
271449,
271457,
271486,
271498,
271537,
271554,
271570,
271572,
271579,
271599,
271605,
271615,
271633,
271638,
271662,
271666,
271681,
271721,
271728,
271745,
271766,
271771,
271793,
271799,
271803,
271834,
271838,
271861,
271864,
271869,
271920,
271921,
271931,
271934,
271953,
271960,
271980,
271984,
271988,
271997,
272068,
272086,
272089,
272098,
272101,
272115,
272128,
272136,
272143,
272166,
272181,
272206,
272237,
272239,
272240,
272259,
272278,
272323,
272349,
272360,
272364,
272365,
272366,
272368,
272380,
272394,
272407,
272417,
272468,
272485,
272490,
272516,
272530,
272540,
272559,
272605,
272609,
272610,
272622,
272626,
272632,
272669,
272674,
272676,
272705,
272752,
272753,
272770,
272800,
272829,
272861,
272865,
272883,
272897,
272914,
272917,
272955,
272984,
273003,
273004,
273020,
273027,
273029,
273034,
273036,
273045,
273047,
273049,
273054,
273085,
273091,
273094,
273108,
273125,
273140,
273161,
273162,
273185,
273195,
273252,
273265,
273273,
273282,
273283,
273295,
273307,
273343,
273347,
273349,
273355,
273360,
273427,
273439,
273452,
273463,
273488,
273492,
273494,
273497,
273516,
273517,
273535,
273554,
273556,
273558,
273568,
273573,
273597,
273623,
273646,
273648,
273656,
273675,
273683,
273690,
273695,
273697,
273742,
273744,
273755,
273763,
273765,
273777,
273778,
273779,
273800,
273838,
273852,
273853,
273856,
273868,
273871,
273872,
273877,
273882,
273899,
273910,
273915,
273925,
273928,
273930,
273938,
273972,
273978,
274014,
274028,
274037,
274057,
274065,
274066,
274098,
274111,
274131,
274133,
274142,
274152,
274154,
274171,
274189,
274191,
274203,
274209,
274216,
274220,
274233,
274262,
274309,
274324,
274326,
274330,
274333,
274335,
274340,
274351,
274382,
274416,
274423,
274437,
274455,
274469,
274528,
274536,
274537,
274545,
274550,
274596,
274629,
274631,
274645,
274667,
274674,
274709,
274726,
274729,
274735,
274744,
274794,
274807,
274818,
274827,
274851,
274872,
274873,
274888,
274897,
274902,
274912,
274915,
274927,
274943,
274947,
274960,
274962,
275007,
275013,
275020,
275023,
275032,
275044,
275054,
275066,
275072,
275073,
275097,
275106,
275109,
275110,
275124,
275125,
275138,
275146,
275150,
275156,
275159,
275171,
275183,
275196,
275211,
275224,
275233,
275236,
275260,
275263,
275284,
275315,
275317,
275318,
275321,
275328,
275348,
275394,
275395,
275401,
275402,
275403,
275422,
275424,
275433,
275458,
275461,
275468,
275471,
275481,
275491,
275493,
275550,
275553,
275554,
275570,
275578,
275579,
275581,
275599,
275607,
275611,
275620,
275633,
275646,
275649,
275652,
275704,
275721,
275746,
275755,
275767,
275769,
275771,
275778,
275781,
275785,
275788,
275825,
275828,
275832,
275843,
275847,
275855,
275876,
275886,
275890,
275892,
275922,
275936,
275939,
275946,
275951,
276002,
276024,
276025,
276030,
276033,
276035,
276043,
276048,
276053,
276078,
276082,
276090,
276100,
276110,
276131,
276132,
276133,
276152,
276163,
276180,
276217,
276224,
276242,
276250,
276255,
276293,
276294,
276310,
276312,
276327,
276330,
276343,
276345,
276379,
276385,
276396,
276407,
276410,
276416,
276420,
276428,
276436,
276440,
276457,
276465,
276484,
276501,
276530,
276535,
276537,
276538,
276555,
276581,
276595,
276609,
276616,
276618,
276625,
276630,
276637,
276640,
276661,
276662,
276684,
276694,
276720,
276728,
276741,
276744,
276753,
276760,
276770,
276783,
276785,
276789,
276792,
276835,
276843,
276846,
276870,
276879,
276888,
276895,
276915,
276931,
276939,
276940,
276949,
276952,
276956,
276966,
276969,
276991,
277011,
277034,
277036,
277043,
277046,
277050,
277068,
277075,
277077,
277085,
277092,
277093,
277115,
277124,
277140,
277147,
277173,
277184,
277188,
277193,
277208,
277217,
277232,
277235,
277254,
277285,
277289,
277298,
277299,
277300,
277307,
277308,
277335,
277343,
277348,
277356,
277357,
277365,
277371,
277380,
277388,
277390,
277413,
277414,
277423,
277426,
277429,
277439,
277445,
277451,
277452,
277460,
277470,
277475,
277485,
277521,
277524,
277528,
277550,
277555,
277568,
277571,
277577,
277594,
277603,
277616,
277654,
277664,
277666,
277678,
277682,
277689,
277702,
277704,
277754,
277771,
277772,
277782,
277783,
277788,
277790,
277802,
277804,
277809,
277817,
277829,
277844,
277846,
277869,
277894,
277895,
277897,
277899,
277911,
277913,
277917,
277924,
277937,
277949,
277950,
277956,
277979,
277982,
277996,
277997,
278007,
278034,
278035,
278047,
278048,
278056,
278067,
278082,
278093,
278104,
278127,
278133,
278134,
278147,
278175,
278182,
278204,
278211,
278251,
278252,
278259,
278264,
278282,
278284,
278287,
278294,
278336,
278344,
278353,
278360,
278364,
278366,
278372,
278387,
278391,
278394,
278424,
278433,
278441,
278459,
278496,
278534,
278543,
278557,
278559,
278571,
278576,
278595,
278596,
278599,
278621,
278631,
278632,
278635,
278639,
278655,
278679,
278683,
278696,
278707,
278709,
278710,
278730,
278758,
278763,
278764,
278770,
278777,
278780,
278789,
278802,
278857,
278865,
278869,
278887,
278892,
278895,
278909,
278954,
278975,
278977,
279009,
279045,
279096,
279098,
279108,
279113,
279118,
279122,
279128,
279158,
279225,
279227,
279240,
279243,
279248,
279264,
279315,
279323,
279327,
279369,
279372,
279390,
279409,
279411,
279420,
279446,
279453,
279455,
279492,
279580,
279587,
279592,
279615,
279617,
279621,
279632,
279638,
279714,
279741,
279742,
279755,
279762,
279771,
279774,
279794,
279802,
279811,
279813,
279833,
279842,
279856,
279864,
279870,
279871,
279909,
279966,
279972,
279985,
279998,
280009,
280019,
280041,
280057,
280085,
280087,
280088,
280094,
280125,
280148,
280149,
280153,
280169,
280172,
280199,
280209,
280211,
280247,
280251,
280256,
280275,
280296,
280331,
280339,
280361,
280380,
280405,
280439,
280457,
280468,
280522,
280528,
280538,
280543,
280570,
280589,
280623,
280642,
280650,
280651,
280677,
280742,
280745,
280750,
280795,
280818,
280834,
280839,
280845,
280856,
280873,
280905,
280910,
280927,
280944,
280947,
280950,
280952,
280960,
281014,
281018,
281022,
281036,
281043,
281045,
281065,
281092,
281104,
281106,
281110,
281120,
281124,
281156,
281183,
281207,
281220,
281237,
281246,
281302,
281303,
281328,
281330,
281333,
281411,
281427,
281433,
281447,
281462,
281503,
281523,
281528,
281550,
281560,
281573,
281578,
281594,
281604,
281606,
281644,
281649,
281652,
281658,
281730,
281743,
281753,
281768,
281769,
281770,
281772,
281792,
281820,
281821,
281823,
281825,
281867,
281878,
281880,
281951,
281954,
281986,
282054,
282077,
282078,
282085,
282093,
282095,
282113,
282118,
282125,
282131,
282144,
282171,
282190,
282210,
282239,
282263,
282282,
282284,
282303,
282312,
282396,
282398,
282431,
282454,
282477,
282493,
282495,
282496,
282510,
282542,
282549,
282577,
282588,
282594,
282604,
282608,
282659,
282668,
282679,
282684,
282686,
282698,
282709,
282714,
282726,
282746,
282807,
282833,
282863,
282878,
282885,
282905,
282937,
282970,
282977,
282985,
282986,
282994,
283017,
283041,
283058,
283072,
283073,
283077,
283091,
283103,
283118,
283165,
283214,
283218,
283227,
283238,
283252,
283254,
283266,
283279,
283283,
283286,
283289,
283290,
283303,
283314,
283315,
283316,
283320,
283334,
283346,
283361,
283372,
283379,
283388,
283399,
283414,
283429,
283439,
283454,
283463,
283466,
283468,
283509,
283522,
283523,
283556,
283585,
283595,
283628,
283651,
283668,
283691,
283693,
283710,
283714,
283722,
283733,
283739,
283751,
283757,
283794,
283804,
283805,
283829,
283830,
283831,
283844,
283882,
283893,
283898,
283923,
284007,
284012,
284019,
284024,
284033,
284041,
284048,
284051,
284056,
284060,
284065,
284068,
284078,
284138,
284141,
284155,
284161,
284171,
284176,
284188,
284192,
284196,
284224,
284231,
284246,
284278,
284288,
284299,
284303,
284311,
284340,
284352,
284404,
284432,
284527,
284542,
284595,
284607,
284613,
284624,
284654,
284686,
284725,
284781,
284832,
284895]);
            $applicationData = $applicationData->whereIn('consumer_application.id', $this->blackSoilApplications);
        }

        if(!Session::has('Agency_Permit|-52')){
            if ($filterData && ($count > 1 || !$request->has('page'))) {
                $applicationData = $applicationData->whereNull('is_deleted');
                $summary = [];/*$application->select(DB::raw('count(consumer_application.id) as count, consumer_application.state'))
                            ->groupBy('consumer_application.state')
                            ->get()->toArray();*/
                if (Auth::user()->user_type == UserTypes::$merchant_v2) {
                    $merchantSearchApplications = $request->get('merchant_id') ?? Auth::user()->merchant_id;
                    $anchorMerchantExist = Merchant::where('anchor_merchant_id',Auth::user()->merchant_id)->pluck('id');
                    $anchorMerchantExist->push(Auth::user()->merchant_id);
                    $data['consumer_applications'] = $applicationData->select('consumer_application.*')->whereIn('merchant_id',$anchorMerchantExist)->orderBy('consumer_application.updated_at', 'desc')->paginate(self::NUM_OF_RECORDS_PER_PAGE);
                }
                if($data['sort_field'] == 'loan_amount'){
                    $applicationData = $applicationData->orderByRaw('CONVERT(consumer_application.loan_amount, SIGNED) '.$data['sort_direction'])->select('consumer_application.*');
                }else{
                    $applicationData = $applicationData->orderByRaw($data['sort_field'].' '.$data['sort_direction'])->select('consumer_application.*');
                }
                // if(count($filterData) > 1) {
                    $data['consumer_applications'] = $applicationData->paginate(self::NUM_OF_RECORDS_PER_PAGE);
                // }else{
                //     $data['consumer_applications'] = $applicationData->limit(self::NUM_OF_RECORDS_PER_PAGE)->get();
                // }

            } else {
                $summary = [];
                if(isset($anchorMerchantExist) && count($anchorMerchantExist)){
                    $anchorMerchantExist->push(Auth::user()->merchant_id);
                    $summary = \App\ConsumerApplication::whereNotNull('state')
                            ->whereNull('is_deleted')->whereIn('merchant_id',$anchorMerchantExist)
                            ->select(DB::raw('count(id) as count, state'))
                            ->groupBy('state')
                            ->get()->toArray();
                    $data['consumer_applications'] = $applicationData->whereNull('is_deleted')->orderBy('consumer_application.updated_at', 'desc')->select('consumer_application.*')->whereIn('merchant_id',$anchorMerchantExist)->paginate(self::NUM_OF_RECORDS_PER_PAGE);
                } else {
                    $applicationData = $applicationData->whereNull('is_deleted')->orderBy('consumer_application.updated_at', 'desc')->select('consumer_application.*');
                }
                if(count($filterData) > 1) {
                    $data['consumer_applications'] = $applicationData->paginate(self::NUM_OF_RECORDS_PER_PAGE);
                }else{
                    $data['consumer_applications'] = $applicationData->limit(self::NUM_OF_RECORDS_PER_PAGE);
                }
                //$data['consumer_applications'] = $applicationData->whereNull('is_deleted')->orderBy('consumer_application.updated_at', 'desc')->select('consumer_application.*');
            }
        }else{
            $agency = AgencyApplication::where('agency_id',Auth::user()->id)->pluck('application_id');
            $summary = [];/*\App\ConsumerApplication::whereNotNull('state')->whereIn('id',$agency)
                ->whereNull('is_deleted')
                ->select(DB::raw('count(id) as count, state'))
                ->groupBy('state')
                ->get()->toArray();*/
            $applicationData = $applicationData->whereNull('is_deleted')->whereIn('id',$agency)->orderBy('consumer_application.updated_at', 'desc')->select('consumer_application.*');
            if(count($filterData) > 1) {
                $data['consumer_applications'] = $applicationData->paginate(self::NUM_OF_RECORDS_PER_PAGE);
            }else{
                $data['consumer_applications'] = $applicationData->limit(self::NUM_OF_RECORDS_PER_PAGE);
            }
        }

        $summarycount = [];
        if(count($summary)) {
            foreach ($summary as $key => $value) {
                $summarycount[strtolower($value['state'])] = $value['count'];
            }
        }
        $merchantData = [];
        $merchantDataItems = [];

        $fullApplications = [];//ConsumerApplication::with('merchant', 'offer')->whereNull('is_deleted')->get(['id']);

        foreach ($fullApplications as $applicationItem) {
            if (isset($applicationItem->merchant)) {
                if (!in_array($applicationItem->state, $this->statusreversearray['approved']) && $applicationItem->offer && $applicationItem->offer->subvention && $applicationItem->merchant->created_at >= '2019-08-07 00:00:00') {
                    $merchantData[$applicationItem->merchant_id][] = $applicationItem;
                }

                if ($applicationItem->merchant && $applicationItem->merchant->vulnerable_merchant) {
                    if ($applicationItem->created_at >= $applicationItem->merchant->vulnerable_merchant_date) {
                        $merchantDataItems[$applicationItem->merchant_id][] = 1;
                    }
                }
            }
        }

        unset($fullApplications);

        $fiveApplicationData = [];
        //$threeApplicationData = [];
        if ($merchantData) {
            foreach ($merchantData as $merchant_id => $merchantDataItem) {
                if (count($merchantDataItem) == 5) {
                    $fiveApplicationData[] = $merchant_id;
                }
          /*      if (count($merchantDataItem) <= 3) {
                    $threeApplicationData[] = $merchant_id;
                }*/
            }
        }

        unset($merchantData);

        if($summarycount) {
            foreach ($this->statusarray as $key => $value) {
                if (isset($summarycount[$key])) {
                    if (!isset($data['summary'][$this->arraygroup[$key]])) {
                        $data['summary'][$this->arraygroup[$key]] = $summarycount[$key];
                    } else {
                        $data['summary'][$this->arraygroup[$key]] = $data['summary'][$this->arraygroup[$key]] + $summarycount[$key];
                    }
                } else {
                    if (!isset($data['summary'][$this->arraygroup[$key]])) {
                        $data['summary'][$this->arraygroup[$key]] = 0;
                    }
                }
            }
        }
        $i = 0;
        if (\Auth::user()->user_type >= 5) {
            array_unshift($this->statusarray['pre approved'], 'approved');
            array_unshift($this->statusarray['pre approved'], 'cf approved');
            array_unshift($this->statusarray['cf approved'], 'approved');
            array_unshift($this->statusarray['waiting for decision'], 'approved');
            array_unshift($this->statusarray['disbursement checklist done'], 'ready for disbursement');
            array_unshift($this->statusarray['disbursement checklist done'], 'disbursement query');
            array_unshift($this->statusarray['ready for disbursement'], 'disbursed');
            array_unshift($this->statusarray['cancelled'], 'disbursed');
        }

        $showOptions = $this->getPermissions();
        $cancellationInProcess = $this->statusarray['cancellation in-process'];
        $userLenderID = 0;
        if(Auth::check() && Auth::user()->lender_id){
            $userLenderID = Auth::user()->lender_id;
        }

        // merchant id is mandatory on the user
        $create_lead_map = Merchant::where('id',Auth::user()->merchant_id)->first(['create_app_lead_on_map','slug','category_id']);
        $data['merchant_create_app_lead'] = $create_lead_map->create_app_lead_on_map ?? '';
        $data['merchant_slug'] = $create_lead_map->slug ?? '';
        $data['category'] = $create_lead_map->category_id ?? 0;

        $pageAppIds = [];
        $allPageAppIds = [];
        foreach ($data['consumer_applications'] as $consumer_applications) {
            $allPageAppIds[] = $consumer_applications->id;

            if(!$consumer_applications->proFormaInvoice){
                $proFormaInvoice = new ProFormaInvoice();
                $proFormaInvoice->application_id = $consumer_applications->id;
                $proFormaInvoice->save();
            }

            $this->statusarray['cancellation in-process'] = $cancellationInProcess;
            //$grade = new GradeController(new Request());
            $statusCheck = array();
            $current_status = strtolower($consumer_applications['state']);
            $current_secondary_status = strtolower($consumer_applications['secondary_status']);

            if ($current_status === 'disbursement query') {
                $pageAppIds[] = $consumer_applications->id;
            }

            if ($current_status == "cancellation in-process") {
                $previous_status = StatusLogs::where('application_id', $consumer_applications->id)->orderBy('created_at', 'desc')->skip(1)->take(1)->get();
                if (isset($previous_status[0]->status)) {
                    array_unshift($this->statusarray['cancellation in-process'], $previous_status[0]->status);
                }
            }
            if (in_array($current_status, ["nach registered", "disbursed"]) && !empty($consumer_applications->secondary_status)) {
                if (($key = array_search('closed', $this->statusarray[$current_status])) !== false) {
                    unset($this->statusarray[$current_status][$key]);
                }
            }
            // if($consumer_applications->id == "13257"){
            //     dd($consumer_applications->application_element->type_of_customer_sub_category );
            // }
            /*if($current_status == 'waiting for decision' && (Auth::user()->user_type == 'operation') || Auth::user()->user_type == 'sales') {
                if (isset($consumer_applications->emi) && $consumer_applications->emi->id) {
                    $_grade = $grade->ApprovalCheckV1($consumer_applications->id);
                    $approvalCheck = $_grade->getOutput();
                    PWAApplicationForm::approvalLog($approvalCheck, $consumer_applications->id);
                    if (empty(array_filter($approvalCheck))) {
                        $statusCheck = $this->statusarray[$current_status];
                        array_unshift($statusCheck, 'approved');
                    }
                }
            }*/

            // Initialize consent flags to 0
            $data['consumer_applications'][$i]['app_consent'] = 0;
            $data['consumer_applications'][$i]['co_app_consent'] = 0;

            // Check applicant consent
            $appConsent = ConsumerApplicationFiles::where([
                ['consumer_application_id', $consumer_applications->id],
                ['file_type', 'consent_logs'],
                ['applicant_type', 1]
            ])->exists();

            if (!$appConsent) {
                $data['consumer_applications'][$i]['app_consent'] = 1;
            }

            // Check co-applicant consent only if co-applicant exists
            if (!empty($consumer_applications->co_applicant_name)) {
                $coAppConsent = ConsumerApplicationFiles::where([
                    ['consumer_application_id', $consumer_applications->id],
                    ['file_type', 'co_app_consent_logs'],
                    ['applicant_type', 2]
                ])->exists();

                if (!$coAppConsent) {
                    $data['consumer_applications'][$i]['co_app_consent'] = 1;
                }
            }

            
            $data['consumer_applications'][$i]['is_edit'] = 0;
            if ($data['consumer_applications'][$i]['is_edit'] == 0) {
                $application_date = Carbon::parse($consumer_applications->created_at);

                $time_from_application = $application_date->diffInMinutes();
                if (!Session::has('Zone_Level_Restriction|-20') || $time_from_application > 15) {
                    $data['consumer_applications'][$i]['is_edit'] = 1;
                } else {
                    $userids = getAvaibleAdvisor($consumer_applications->permanent_address_pincode);
                    if (in_array(\Auth::user()->id, $userids)) {
                        $data['consumer_applications'][$i]['is_edit'] = 1;
                    }
                }

                if ($data['consumer_applications'][$i]['is_edit'] == 0 && (empty($consumer_applications['permanent_address_pincode']) && empty($consumer_applications['permanent_address_pincode']))) {
                    $data['consumer_applications'][$i]['is_edit'] = 1;
                }
            }

            $statusData = ($statusCheck) ? $statusCheck : (isset($this->statusarray[$current_status]) ? $this->statusarray[$current_status] : ['rejected', 'aborted']);
            if (in_array($consumer_applications->lender_id, [Blacksoil::$lender_id, 2])) {
                if (isset($current_secondary_status) && $current_secondary_status) {
                    $secondaryStatusData = isset($this->secondaryStatusArray[$consumer_applications->secondary_status]) ? $this->secondaryStatusArray[$consumer_applications->secondary_status] : null;
                } else {
                    $secondaryStatusData = isset($this->secondaryStatusArray[$current_status]) ? $this->secondaryStatusArray[$current_status] : null;
                }
                if ($secondaryStatusData) {
                    $statusData = array_merge($statusData, $secondaryStatusData);
                    $statusData = collect($statusData)->unique()->values()->all();
                    if (isset($current_secondary_status) && $current_secondary_status && $current_secondary_status != 'settlement-aborted') {
                        $statusData = array_filter($statusData, function($value) {
                            return $value !== 'closed';
                        });
                    }
                }
                if (isset($current_secondary_status) && in_array($current_secondary_status, ['settled', 'settlement-done'])) {
                    $settlement_in_progress_key = array_search('settlement-in-progress', $statusData);
                    unset($statusData[$settlement_in_progress_key]);
                }
            }

            if(isset($statusData['cf approved'])){
                //Commented due to server load
                /*$avanse = new AvanseProcesses($request);
                $statusData = $avanse->isAvanseEligible($statusData);*/
            }

            $coapplicant_siging = 0;
            if ((isset($consumer_applications->merchant->co_applicant) && $consumer_applications->merchant->co_applicant == 1) || (isset($consumer_applications->application_element->co_applicant_for_signing) && $consumer_applications->application_element->co_applicant_for_signing == 1)) {
                $coapplicant_siging = 1;
            }

            if (isset($consumer_applications->application_element->co_applicant_for_signing) && $consumer_applications->application_element->co_applicant_for_signing == 2) {
                $coapplicant_siging = 0;
            }

            $co_applicant_for_income = 0;
            if ((isset($consumer_applications->application_element->co_applicant_for_income) && $consumer_applications->application_element->co_applicant_for_income == 1)) {
                $co_applicant_for_income = 1;
            }

            if ($co_applicant_for_income == 1) {
                $coapplicant_siging = 0;
            }

                $statusData = array_filter(array_map(function ($status) use ($showOptions) {
                return (array_search($status, $showOptions)) !== false ? $status : '';
            }, $statusData));


            if($consumer_applications->mobile_number) {
                //$telecome_data = TelecomData::where('mobile_number', wall_decrypt($consumer_applications->mobile_number))->first(['telecom_response']);
            }

            $sanctionAmountLogs = SanctionAmountLogs::where('application_id', $consumer_applications->id)->orderBy('created_at', 'desc')->first(['approved_amount', 'is_esing_done']);
            $data['consumer_applications'][$i]['sanction_amount_changed'] = isset($sanctionAmountLogs->approved_amount) && $sanctionAmountLogs->approved_amount < $consumer_applications->approved_amount && !$sanctionAmountLogs->is_esing_done ? 1 : 0;
            if($data['consumer_applications'][$i]['sanction_amount_changed']){
                $per10Upper = ($sanctionAmountLogs->approved_amount * 10/100) + $sanctionAmountLogs->approved_amount;
                $data['consumer_applications'][$i]['sanction_amount_changed'] = 0;
                if($consumer_applications->approved_amount >= $per10Upper) {
                    $data['consumer_applications'][$i]['sanction_amount_changed'] = 1;
                }
            }




            $data['consumer_applications'][$i]['telecom_data'] = (isset($telecome_data->telecom_response)) ? json_decode(json_decode(wall_decrypt($telecome_data->telecom_response))) : '';
            $data['consumer_applications'][$i]['statusarray'] = $statusData;
            $data['consumer_applications'][$i]['statusgroup'] = isset($this->arraygroup[$current_status]) ? $this->arraygroup[$current_status] : 'rejected';
            $data['consumer_applications'][$i]['pastLogs'] = [];//$this->getPastLogs($consumer_applications);
            $data['consumer_applications'][$i]['is_cpv_required'] = [];//$this->getCPVStatus($consumer_applications);
            //$_pending = $this->pendingDoc($consumer_applications, ['co_applicant_for_signing' => $coapplicant_siging, 'co_applicant_for_income' => $co_applicant_for_income]);
            $data['consumer_applications'][$i]['pendingDoc'] = [];//$_pending['document'];
            $data['consumer_applications'][$i]['completePendingDoc'] = [];//$_pending['docsRequired'];
            $data['consumer_applications'][$i]['co_applicant_for_signing'] = $coapplicant_siging;
            $data['consumer_applications'][$i]['co_applicant_for_income'] = $co_applicant_for_income;
            $data['consumer_applications'][$i]['is_existing'] = []; // $this->isExistingCustomer($consumer_applications->id);
            $data['consumer_applications'][$i]['disb_post_installation'] = isset($consumer_applications->merchant->id) && $consumer_applications->merchant->disb_post_installation == 1;//$this->isDisbPostInstallationCase($consumer_applications->id);
            if ($data['consumer_applications'][$i]['is_existing']) {
                $data['consumer_applications'][$i]['is_nach_required'] = [];//$nachService->isCustomerHasPreviousActiveNach($consumer_applications->applicant_id);
            }
            $data['consumer_applications'][$i]['call_list'] = [];//$this->getCallerLists($consumer_applications);
            if (isset($consumer_applications->offer->disbursementOffer) && count($consumer_applications->disbursementOfferDisbursed)) {
                $phaseCount = $this->getMultiStageDisbursementStatus($consumer_applications);
                $phaseCountDisbursed = $this->getDisbursementPhasesDisbursed($consumer_applications);
                $phaseCount = str_replace('Phase ','',$phaseCount);
                if(intval($phaseCount) <= count($consumer_applications->disbursementOfferDisbursed)){
                    $data['consumer_applications'][$i]['partial_disbursement'] = $this->getMultiStageDisbursementStatus($consumer_applications);
                }
                if ($phaseCountDisbursed < count($consumer_applications->disbursementOfferDisbursed)){
                    $data['consumer_applications'][$i]['isPartiallyDisbursed'] = true;
                } else {
                    $data['consumer_applications'][$i]['isPartiallyDisbursed'] = false;
                }
            }

            //$payoutStatus = PayoutStatus::where('application_id', $consumer_applications->id)->first(['status']);
            if(isset($consumer_applications->payoutStatus) && isset($consumer_applications->payoutStatus->status) && $consumer_applications->payoutStatus->status == 'FAILURE') {
                $data['consumer_applications'][$i]['isPaytmFailed'] = 1;
            }else if($consumer_applications->CFPayoutDirectTransfer){
                if(isset($consumer_applications->CFPayoutDirectTransfer) && isset($consumer_applications->CFPayoutDirectTransfer->acknowledged) && !in_array($consumer_applications->CFPayoutDirectTransfer->acknowledged, [1,0])) {
                    $data['consumer_applications'][$i]['isPaytmFailed'] = 1;
                }
            }
            $isSignedDA = false;
            $file = ConsumerApplicationFiles::where('consumer_application_id', $consumer_applications->id)->where('file_type', 'pro_forma_invoice')->whereNull('deleted_at')->whereNotNull('created_by')->where('created_by', '!=', 107)->first(['id']);

            if (isset($file->id)){
                $isSignedDA = true;
            }

            $data['consumer_applications'][$i]['isHypothecationDone'] = false;
            $data['consumer_applications'][$i]['isHypothecationActivated'] = false;
            $apiController = new ApiController();
            $isHypothecationActive = $apiController->canHypothecated($consumer_applications->id);
            if ($isHypothecationActive){
                $data['consumer_applications'][$i]['isHypothecationActivated'] = true;

                if($isSignedDA){
                    $data['consumer_applications'][$i]['isHypothecationDone'] = true;
                }
            }
            if (in_array(strtolower($current_status), ['approved', 'disbursement checklist done', 'ready for disbursement', 'disbursed', 'nach registered', 'disbursement query'])) {
                if (isset($consumer_applications->bank_details)) {
                    $bank_names = array_keys(\Illuminate\Support\Facades\Config::get('constants.emandate_bank_list'));
                    if (in_array($consumer_applications->bank_details->bank_name, $bank_names)) {
                        $mandate = Mandate::where('mode', 'lotuspay_emandate')->where('consumer_application_id', $consumer_applications->id)->where('status', '=', 'active')->count();
                        $consumerDoc = ConsumerApplicationFiles::where('consumer_application_id', $consumer_applications->id)->wherenull('deleted_at')->where(function ($query) {
                            $query->where('file_type', 'like', '%nach%')
                            ->orWhere('file_type', 'like', '%mandate%')
                            ->orWhere('file_type', 'like', '%emandate%');
                        })->count();
                        if ($mandate < 1 && $consumerDoc < 1) {
                            $data['consumer_applications'][$i]['pendingDoc'] = array_merge($data['consumer_applications'][$i]['pendingDoc'], array('emandate' => false));
                        }
                    }
                }
                $frontcntrller = new FrontController($request);
                $data['consumer_applications'][$i]['payment_modal_values'] = [];//$frontcntrller->getFeesData($consumer_applications->id);
                $hashids = new Hashids('Creditfair by CS', 20);
                $data['consumer_applications'][$i]['esign_link'] = asset('esign/'. $hashids->encode($consumer_applications->id) . '?type=1');
            }
            // dd($consumer_applications->category->id);
            if (isset($consumer_applications->category->id) && $consumer_applications->category->id == _env('SOLAR_CATEGORY_ID')){
                $data['consumer_applications'][$i]['isSolarCase'] = true;

            }else{
                $data['consumer_applications'][$i]['isSolarCase'] = false;
            }


            foreach ($consumer_applications->comments as $index => $commentData) {
                if (isset($commentData->comment)) {
                    if($userLenderID && $commentData->show_avanse != $userLenderID){
                        unset($data['consumer_applications'][$i]->comments[$index]);
                        continue;
                    }
                    $data['consumer_applications'][$i]->comments[$index]->comment = ApiController::getPureComment(new Request(['comment' => $commentData->comment]))['comment'];
                }
            }

            $consumer_applications->risk_mitigation_flags = [];
    
            if (isset($consumer_applications->application_element->merchant_risk_mitigation)) {
                $risk_json = json_decode($consumer_applications->application_element->merchant_risk_mitigation, true);
                
                if (json_last_error() === JSON_ERROR_NONE && is_array($risk_json)) {
                    $consumer_applications->risk_mitigation_flags = $risk_json;
                }
            }

            $i++;
        }
        foreach ($merchantDataItems as $_key_merchant_id => $_merchantDataItems) {
            if (count($_merchantDataItems) >= 6) {
                $this->unsetMerchantVulnerableMerchant($_key_merchant_id);
            }
        }


        $data['consumer_applications'] = $this->sortApplications($data['consumer_applications'], $fiveApplicationData);
        unset($fiveApplicationData);

        $data['status'] = $this->status;
        $data['combine_application'] = $data['_application_status'] == '' ? [] : $data['_application_status'];
        $data['combine_secondary_application'] = $data['_application_secondary_status'] == '' ? [] : $data['_application_secondary_status'];
        $data['combine_merchant'] = $data['_merchant_id'] == '' ? [] : $data['_merchant_id'];
        $data['helptext'] = $this->helptext;
        $data['merchants'] = Merchant::where('is_guest_active', 1);
        if(Auth::check() && Auth::user()->lender_id == AvanseServices::$lender_id){
            $data['merchants'] = $data['merchants']->whereIn('id', AvanseProcesses::activatedMerchants());
        }
        $bnpl_merchants = BNPL::getMerchants();
        if(($request->has('application_type') && $request->get('application_type') == 'bnpl') || strpos($request->path(),'bnpl-application')) {
            $data['merchants'] = $data['merchants']->whereIn('id', $bnpl_merchants);
        }else{
            if (Auth::user()->user_type == UserTypes::$merchant_v2) {
                if(isset($anchorMerchantExist) && count($anchorMerchantExist)){
                    $anchorMerchantExist->push(Auth::user()->merchant_id);
                    $data['merchants'] = $data['merchants']->whereIn('id', $anchorMerchantExist);
                }else{
                    $data['merchants'] = $data['merchants']->where('id', Auth::user()->merchant_id);
                }
            } else {
                $data['merchants'] = $data['merchants']->whereNotIn('id', $bnpl_merchants);
            }
        }
        if(count(array_filter($selected_categories)) && Auth::user()->user_type != UserTypes::$merchant_v2){
            $data['merchants'] = $data['merchants']->whereIn('category_id', $selected_categories)->orderBy('merchant_name', 'asc')->whereNull('deleted_at')->get(['id', 'merchant_name']);
        }else{
            $data['merchants'] = $data['merchants']->orderBy('merchant_name', 'asc')->whereNull('deleted_at')->get(['id', 'merchant_name']);
        }
        $data['merchant_category'] = MerchantCategory::all();
        $data['inverter_list'] = $this->inverterList();
        $data['panel_list'] = $this->panelList();
        $data['service_provider_list'] = $this->serviceProviderList();
        $data['negativeProfile'] = NegativeProfile::all();
        $data['users'] = User::where('user_type', '>=', 5)->whereNull('deleted_at')->get(['id', 'name']);
        $data['application_status'] = array_map('ucfirst', array_keys($this->arraygroup));
        $data['secondary_status'] = array_map('ucfirst', array_keys($this->secondaryStatusArray));
        $data['lenders'] = Lenders::orderBy('id','desc')->get();
        $data['sources'] = ConsumerApplication::where('is_deleted')->groupBy('updated_by')->get(['updated_by as source']);
        $data['source_name'] = $request->get('source');
        $data['after_approval_status'] = $this->statusreversearray['approved'];
        $data['advisors'] = $data['users'];
        $data['more_filters'] = $request->all();
        $data['merchantDataItems'] = $merchantDataItems;
        $data['mr_exclude_in'] = $request->get('mr_exclude_in') ? $request->get('mr_exclude_in') : 0;
        $data['src_exclude_in'] = $request->get('src_exclude_in') ? $request->get('src_exclude_in') : 0;
        //        $data['sources'] = ConsumerApplication::where('is_deleted')->groupBy('updated_by')->get(['updated_by as source']);
        $supported_bank = (new NachSupportedBank())->getBankLists();
        $data['supported_bank'] = array_map('strtolower', $supported_bank);
        $data['source_name'] = $request->get('source');
        $data['field_sort'] = ['id' => 'App Id', 'name'=>'Full Name', 'loan_amount'=>'Loan Amount', 'updated_at' => 'Latest Updated', 'created_at'=>'Latest Created'];
        $data['direction_sort'] = ['asc' => 'Ascending','desc' => 'Descending'];
        //permission to create application
        $data['permission_to_create_application'] = 0;
        /*if(!isset($merchantItems)){
            $summary_new_merchant = ConsumerApplication::whereNull('is_deleted')->groupBy('merchant_id')->having(DB::raw('count(merchant_id)'), '<=', 5)->having(DB::raw('count(merchant_id)'), '>', 0)->get(['merchant_id', DB::raw('count(merchant_id) as app_received')]);
            $isNewFiveApplicationFilterDataMerchant = [];
            foreach ($summary_new_merchant as $summary_new_merchantItem){

                if($summary_new_merchantItem->app_received == 5){
                    $hasCount = ConsumerApplication::where('merchant_id', $summary_new_merchantItem->merchant_id)->whereIn('state', $this->statusreversearray['approved'])->whereNull('is_deleted')->get(['id']);
                    if(count($hasCount)) {
                        $isNewFiveApplicationFilterDataMerchant[] = $summary_new_merchantItem->merchant_id;
                    }
                }else{
                    $isNewFiveApplicationFilterDataMerchant[] = $summary_new_merchantItem->merchant_id;
                }
            }

            $merchantItems = Merchant::whereIn('id',$isNewFiveApplicationFilterDataMerchant)->where('status','active')->where('is_guest_active', 1)->whereNull('deleted_at')->get(['id']);

            $data['summary']['new merchant'] = count($merchantItems);
        }else{
            $data['summary']['new merchant'] = count($merchantItems);
        }*/

        if($isNewFiveApplicationFilter){
            $data['isNewFiveApplicationFilterStatus'] = $isNewFiveApplicationFilter;
        }
        $data['vkyc_type'] = self::VKYC_VENDOR;

        if (!empty($pageAppIds)) {
            $data['caseReviewRequestAppIds'] = CaseReviewRequest::getAppIdsWithRequests($pageAppIds);
            $data['caseReviewPendingCounts'] = CaseReviewRequest::getPendingCountsForApps($pageAppIds);
        } else {
            $data['caseReviewRequestAppIds'] = [];
            $data['caseReviewPendingCounts'] = [];
        }

        if (!empty($allPageAppIds)) {
            $data['disbDeviationPendingCounts'] = ApplicationDeviation::getPendingDisbDeviationCountsForApps($allPageAppIds);
        } else {
            $data['disbDeviationPendingCounts'] = [];
        }
        
        $appIds = $data['consumer_applications']->pluck('id')->toArray();
        $data['approvalLogs'] = StatusLogs::whereIn('application_id', $appIds)
            ->where('status', 'approved')
            ->orderBy('created_at', 'asc')
            ->get()
            ->keyBy('application_id');

        // dd($data);

        return view('admin.consumer-application.index', $data);
    }

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

        $data = [];
        $consumer_applications = ConsumerApplication::with('payoutStatus', 'CFPayoutDirectTransfer','user','checkmandate', 'offer.disbursementOffer', 'documents', 'logs', 'digital_sign', 'merchant', 'merchant.anchorMerchant', 'merchant.merchant_category', 'category', 'emi', 'creditReport', 'application_element.merchant_center', 'advisor', 'comments.user', 'bank_details','proFormaInvoice', 'lender')->where('id', $id)->get();

        $nachService = new NachService($request);

        foreach ($consumer_applications as $application) {


            $coapplicant_siging = 0;
            if ((isset($application->merchant->co_applicant) && $application->merchant->co_applicant == 1) || (isset($application->application_element->co_applicant_for_signing) && $application->application_element->co_applicant_for_signing == 1)) {
                $coapplicant_siging = 1;
            }

            if (isset($application->application_element->co_applicant_for_signing) && $application->application_element->co_applicant_for_signing == 2) {
                $coapplicant_siging = 0;
            }

            $co_applicant_for_income = 0;
            if ((isset($application->application_element->co_applicant_for_income) && $application->application_element->co_applicant_for_income == 1)) {
                $co_applicant_for_income = 1;
            }

            if ($co_applicant_for_income == 1) {
                $coapplicant_siging = 0;
            }


            $data[$application->id]['id'] = $application->id;
            $data[$application->id]['referred_by'] = $application->user ? $application->user->referred_by : '';
            $data[$application->id]['mobile_number'] = $application->mobile_number;
            $data[$application->id]['pastLogs'] = $this->getPastLogs($application);
            $data[$application->id]['is_cpv_required'] = $this->getCPVStatus($application);
            $_pending = $this->pendingDoc($application, ['co_applicant_for_signing' => $coapplicant_siging, 'co_applicant_for_income' => $co_applicant_for_income, 'credit_appraisal_memo' => in_array($application->state,$this->statusreversearray['approved']) ? false : true]);
            $data[$application->id]['pendingDoc'] = $_pending['document'];
            $data[$application->id]['completePendingDoc'] = $_pending['docsRequired'];
            $data[$application->id]['is_existing'] = $this->isExistingCustomer($application->id);
            $data[$application->id]['call_list'] = $this->getCallerLists($application);
            $data[$application->id]['merchant_status_symbol'] = $application->merchant && $application->merchant->status == 'active' && $application->merchant->pre_status == 1 ? 1 : 0;
            $data[$application->id]['is_insurance_taken'] = isset($application->proFormaInvoice->insurance_premium_amount) && !empty($application->proFormaInvoice->insurance_premium_amount) ? 1 : 0;
            $statusMessagePayout = '';
            if($application->payoutStatus && $application->payoutStatus->status == 'FAILURE'){
                $PayoutStatus = PayoutStatus::where('application_id', $application->id)->where('retry', 0)->first(['id']);
                if(isset($PayoutStatus->id)) {
                    $payoutPreserve = PayoutPreserve::where('payout_status_id', $application->payoutStatus->id)->orderBy('created_at', 'desc')->first(['response']);
                    if (isset($payoutPreserve->response) && $payoutPreserve->response) {
                        $payoutData = json_decode($payoutPreserve->response);
                        $statusMessagePayout = $payoutData->statusMessage;
                    }
                }
            }else if($application->CFPayoutDirectTransfer && isset($application->CFPayoutDirectTransfer->acknowledged) && !in_array($application->CFPayoutDirectTransfer->acknowledged, [1,0]) && !$application->CFPayoutDirectTransfer->retry){
                $statusMessagePayout = $application->CFPayoutDirectTransfer->message;
            }
            $data[$application->id]['is_paytm_fail'] = $statusMessagePayout;
            if ($data[$application->id]['is_existing']) {
                $data[$application->id]['is_nach_required'] = $nachService->isCustomerHasPreviousActiveNach($application->applicant_id);
            }
            $data[$application->id]['ptp'] = $this->getPTPDetails($application);
        }

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

    public function deletePTPDate(Request $request){
        $promiseToPay = PromiseToPay::where('id', $request->get('id'))->delete();

        if($promiseToPay){
            $promiseToPay = PromiseToPay::with('user')->where('application_id', $request->get('application_id'))->get();
            return \response(['status' => 'OK', 'message' => 'PTP Date successfully deleted', 'lists' => ['ptp' => ['lists' => $promiseToPay], 'color' => 'red']]);
        }

        return \response(['status' => 'FAIL', 'message' => 'Failed to delete PTP Date']);
    }

    public function getPTPDetails($application){

        $show = false;
        $promiseToPay = [];
        if(in_array($application->state, ['disbursed','nach registered'])) {
            $promiseToPay = PromiseToPay::with('user')->where('application_id', $application->id)->get();
            $show = true;
        }

        $data = [
            'show' => $show,
            'color' => count($promiseToPay) ? 'red' : 'green',
            'lists' => $promiseToPay
        ];

        return $data;
    }


    public function sendConsentMessageToCustomer($id){
        $element = ConsumerApplicationElement::where('application_id', $id)->where('is_consent', 1)->first(['id']);
        if(!isset($element->id)) {
            $lenderService = new LenderServices(new Request());
            $lenderService->sendConstantMessage($id);
            \Session::flash('success', 'Consent link sent to customer successfully');
            return \redirect()->back();
        }
        \Session::flash('error', 'Consent already taken!!');
        return \redirect()->back();
    }

    public function sendConsentMessageToCustomerCoApp($id){
        $element = ConsumerApplicationElement::where('application_id', $id)->where('is_co_app_consent', 1)->first(['id']);
        if(!isset($element->id)) {
            $lenderService = new LenderServices(new Request());
            $lenderService->sendConstantMessage($id,2);
            \Session::flash('success', 'Consent link sent to Co Applicant successfully');
            return \redirect()->back();
        }
        \Session::flash('error', 'Consent already taken!!');
        return \redirect()->back();
    }

    public function sendLegalChargesLinkToCustomer($application_id){
        $application = ConsumerApplication::with('emi','merchant')->where('id', $application_id)->first();

        $legal_charges_initial_date = "2025-01-13"; // Default date value set according to the stamp duty release
        $approvedLog = StatusLogs::where('application_id', $application_id)->where('status', 'approved')->orderBy('created_at', 'asc')->first(['created_at']);
        $legalChargesReleaseDate = Carbon::parse($legal_charges_initial_date);
        if ($approvedLog) {
            $approvedDate = Carbon::parse($approvedLog->created_at);
            if ($legalChargesReleaseDate->gt($approvedDate)) {
                \Session::flash('error', 'Legal Charges link not sent!!');
                return \redirect()->back();
            }
        }

        $apiController = new ApiController();
        $isHypothecationActive = $apiController->canHypothecated($application_id);
        if ($isHypothecationActive) {
            $merchant_id = isset($application->merchant_id) ? $application->merchant_id : null;
            $categoryRules = MerchantCategoryLegalCharges::where('category_id', $application->purpose)->orderBy('created_at','desc')->first();
            if ($application->lender_id == Singularity::$lender_id) {
                $legalChargesCheckAmount = $application->approved_amount - $application->emi->upfront_from_customer ?? 0;
            } else {
                $legalChargesCheckAmount = $application->approved_amount;
            }
            $conditionMet = $this->evaluateLegalChargesCondition($legalChargesCheckAmount, $categoryRules->condition, $categoryRules->net_loan_amount, $merchant_id, $application_id);
            if($conditionMet){
                $legalChargesAmount = $categoryRules->legal_charges;
                $exceptional_ids = explode(',',_env('STAMP_SERIES_SPECIFIC_CASES'));
                if($legalChargesCheckAmount > 500000 || in_array($application_id, $exceptional_ids)) {
                    $legalChargesAmount = 300;
                }
                if(isset($legalChargesAmount) && $legalChargesAmount > 0) {
//                    $legalChargesAmount = $legalChargesAmount + $this->legalChargesProcessingFee;
                    $link = $this->sendLegalChargesLink($legalChargesAmount, $application);
                    $short_link = Shortio::getUrl($link);

                    if (isset($application->email)) {
                        $body = '
                        <div style="font-size:13px;font-family:verdana,arial;line-height:1.5">
                        Dear ' . $application->name . ',
                        Kindly pay the legal charges for your loan ID ' . $application->id . ' on ' . Carbon::now()->toDateTimeString() . ' . Payment link for legal charges
                        <table style="width:100%"><tbody><tr>
                        <td align="center" style="padding:30px 30px 30px 30px">
                        <table cellpadding="0" cellspacing="0" border="0">
                        <tbody><tr>
                        <td align="center" style="border-radius:3px;background-color:#0055cc;padding:11px 26px">
                        <a href="' . $short_link . '?em=true" style="color:white;text-decoration:none;text-transform:uppercase;font-size:16px" target="_blank" data-saferedirecturl="https://www.google.com/url?q=https://capitaluat.creditfair.in/login&amp;source=gmail&amp;ust=1637060221906000&amp;usg=AOvVaw3bBoklT_FpqO9DEsYxRg0q">
                         Pay Legal Charges</a>
                        </td></tr>
                        </tbody></table>
                        </td></tr></tbody></table>
                        Please note it can take up to 3 working days to update payment in our system post debit from your account.
                        </div>';

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

                    // $merchant_name = $merchant->merchant_name;
                    $sms_body = "Dear ".$application->name.", Kindly make the payment for the legal document charges on the purchase made at  ".$application->merchant->merchant_name.". ".$short_link." - Regards, Team Credit Fair.";
                    $args = [$application->name, $application->merchant->merchant_name, $short_link];
                    $entity = ['templateid' => '1307172665882209662', 'entityid' => Templates::$entityid];

                    send_sms($application->mobile_number, ['message' => $sms_body,'id'=>$application->id,'id_type'=>'application_id',
                        'templateDetails' => $entity, 'args' => $args]);

                    \Session::flash('success', 'Legal Charges link sent to customer successfully');
                    return \redirect()->back();
                }
            }
        }

        \Session::flash('error', 'Legal Charges link not sent!!');
        return \redirect()->back();
    }

    public function evaluateLegalChargesCondition($loanAmount, $condition, $netLoanAmount, $merchant_id = null, $application_id = null)
    {
        $exceptional_ids = explode(',',_env('STAMP_SERIES_SPECIFIC_CASES'));
        if($loanAmount > 500000 || (isset($application_id) && in_array($application_id, $exceptional_ids))){
            return true;
        }
        switch ($condition) {
            case 'loan_amount_less_than':
                return $loanAmount <= $netLoanAmount;
            case 'loan_amount_more_than':
                return $loanAmount > $netLoanAmount;
            default:
                return false;
        }
    }

    public function sendMessageBeforeBureauPull($id){

        $customer = ConsumerApplication::where('id',$id)->first(['co_applicant_name']);
        $lenderService = new LenderServices(new Request());
        $lenderService->sendConstantMessage($id);
        if(isset($customer->co_applicant_name)){
            $lenderService->sendConstantMessage($id,2);
        }
        return true;
    }

    public function getPermissions()
    {
        $statusPermissions = Session::all();
        $showOptions = [];
        foreach ($statusPermissions as $permission => $item) {
            if (!is_array($permission) && strpos($permission, '|#') !== false) {
                $showOptions[] = str_replace('_', ' ', explode('|#', $permission)[0]);
            }
        }
        return $showOptions;
    }

    public function getLenderPermissions()
    {
        $statusPermissions = Session::all();
        $showOptionsLenders = [];
        foreach ($statusPermissions['permissions'] as $permission => $item) {
            if (!is_array($permission) && strpos($item, '|*') !== false) {
                $showOptionsLenders[] = str_replace('_', ' ', explode('|*', $item)[0]);
            }
        }
        return $showOptionsLenders;
    }

    public function getStatusVisibilityPermissions()
    {
        $statusPermissions = Session::all();
        $showOptionsVisibleStatus = [];
        foreach ($statusPermissions as $permission => $item) {
            if (!is_array($permission) && strpos($permission, '|%') !== false) {
                $showOptionsVisibleStatus[] = str_replace('_', ' ', explode('|%', $permission)[0]);
            }
        }
        return $showOptionsVisibleStatus;
    }

    public function unsetMerchantVulnerableMerchant($id)
    {
        $merchant = Merchant::find($id);
        $merchant->vulnerable_merchant = 0;
        $merchant->vulnerable_merchant_date = null;
        $merchant->save();
    }

    public function getDisbursementPhasesDisbursed($application)
    {
        $disbursementStage = DisbursementLogs::isPartialDisbursement($application);
        if (is_bool($disbursementStage))
            return $disbursementStage;
        $disbursementStageValue = (in_array($application->state, ['disbursed', 'nach registered']) && isset($disbursementStage) ) ? count($disbursementStage) : 0;
        return $disbursementStageValue;
    }

    public function getMultiStageDisbursementStatus($application)
    {
        $disbursementStage = DisbursementLogs::isPartialDisbursement($application);
        if (is_bool($disbursementStage))
            return $disbursementStage;
        $disbursementStageString = (!in_array($application->state, ['disbursed', 'nach registered']) && count($disbursementStage) == 1) ? count($disbursementStage) : (count($disbursementStage) + 1);
        return 'Phase ' . $disbursementStageString;
    }

    public function getCallerLists($application, $user_type = '', $isApp = false, $raw = false)
    {
        $lists = [];


        $discardNumber = (Auth::user()) ? Auth::user()->mobile_number : 0;

        $mobileNumber = [];

        if ($user_type) {
            $userData = User::find($user_type);
            if (isset($userData->mobile_number)) {
                $discardNumber = $userData->mobile_number;
                $user_type = $userData->user_type;
            }
        }

        if (isset($application->mobile_number) && !$isApp) {
            if ($application->mobile_number && $application->mobile_number != $discardNumber && !in_array($application->mobile_number, $mobileNumber)) {
                $lists[] = ['name' => $application->name, 'phone' => $application->mobile_number, 'type' => 'Applicant'];
                array_push($mobileNumber, $application->mobile_number);
            }
        }
        if (isset($application->co_applicant_mobile_number) && $application->co_applicant_mobile_number != $discardNumber && !$isApp) {
            if ($application->co_applicant_mobile_number && !in_array($application->co_applicant_mobile_number, $mobileNumber)) {
                $lists[] = ['name' => $application->co_applicant_name, 'phone' => $application->co_applicant_mobile_number, 'type' => 'Co-Applicant'];
                array_push($mobileNumber, $application->co_applicant_mobile_number);
            }
        }

        if (isset($application->application_element->reference_contact_1) && !$isApp) {
            if ($application->application_element->reference_contact_1 && $application->application_element->reference_contact_1 != $discardNumber && !in_array($application->application_element->reference_contact_1, $mobileNumber)) {
                $lists[] = ['name' => $application->application_element->reference_name_1, 'phone' => $application->application_element->reference_contact_1, 'type' => 'Reference 1'];
                array_push($mobileNumber, $application->application_element->reference_contact_1);
            }
        }

        if (isset($application->application_element->reference_contact_2) && !$isApp) {
            if ($application->application_element->reference_contact_2 && $application->application_element->reference_contact_2 != $discardNumber && !in_array($application->application_element->reference_contact_2, $mobileNumber)) {
                $lists[] = ['name' => $application->application_element->reference_name_2, 'phone' => $application->application_element->reference_contact_2, 'type' => 'Reference 2'];
                array_push($mobileNumber, $application->application_element->reference_contact_2);
            }
        }

        if (empty($user_type) || ($user_type > 4)) {
            if ($application->src_representative_name) {
                $user = User::find($application->src_representative_name);
                if (isset($user->mobile_number) && $user->mobile_number != $discardNumber && !in_array($user->mobile_number, $mobileNumber)) {
                    $type = MerchantApiController::getUserTypeString($user->user_type);
                    $userNameData = $user->user_type;
                    if($type == 'Admin') {
                        $userName = UserTypes::where('id', $user->user_type)->first(['name']);
                        $userNameData = isset($userName->name) ? $userName->name : $user->user_type;
                    }
                    $type = $type == 'Admin' ? $userNameData : $type;
                    $lists[] = ['name' => $user->name, 'phone' => $user->mobile_number, 'type' => ucwords(str_replace('_', ' ', $type))];
                    array_push($mobileNumber, $user->mobile_number);
                }
            }
            if ($application->application_element && $application->application_element->center_id) {
                $location = MerchantLocation::where('id', $application->application_element->center_id)->first(['phone', 'name']);
                if (isset($location->phone) && $location->phone != $discardNumber && !in_array($location->phone, $mobileNumber)) {
                    $lists[] = ['name' => $location->name, 'phone' => $location->phone, 'type' => 'Center'];
                    array_push($mobileNumber, $location->phone);
                }
            }
            if ($application->merchant_id) {
                $merchant = Merchant::find($application->merchant_id);
                if (isset($merchant->contact_number) && !empty($merchant->contact_number) && $merchant->contact_number != $discardNumber && !in_array($merchant->contact_number, $mobileNumber)) {
                    $lists[] = ['name' => $merchant->owner_name, 'phone' => $merchant->contact_number, 'type' => 'Merchant'];
                    array_push($mobileNumber, $merchant->contact_number);
                }
            }
        } else {
            if ($application->created_by) {
                $user = User::find($application->created_by);
                if (isset($user->mobile_number) && $user->mobile_number != $discardNumber && !in_array($user->mobile_number, $mobileNumber)) {
                    $lists[] = ['name' => $user->name, 'phone' => $user->mobile_number, 'type' => 'Advisor'];
                    array_push($mobileNumber, $user->mobile_number);
                }
            }
        }

        if ($isApp || $raw) {
            return $lists;
        }

        return ($lists) ? '<ul>' . implode('', array_map(function ($item) use ($application) {
                return "<li class='exotel-call' data-type='application_id' data-user-type='" . $item['type'] . "'  data-id=" . $application->id . " data-contact=" . $item['phone'] . ">" . $item['name'] . ", " . $item['type'] . "</li>";
            }, $lists)) . '</ul>' : '';
    }

    public function sortApplications($applications, $fiveApplicationData = array())
    {

        $merchants = [];
        foreach ($applications as $key => $application) {
            if (!in_array($application->merchant_id, $merchants)) {
                $last_seen = ConsumerApplication::where('merchant_id', $application->merchant_id)->orderBy('created_at', 'desc')->limit(2)->get(['created_at']);
                if (count($last_seen) > 1) {
                    $applications[$key]['last_seen'] = $this->dateToTimeString($last_seen[1]->created_at, Carbon::now()->toDateTimeString());
                    $merchants[] = $application->merchant_id;
                } else {
                    $applications[$key]['last_seen'] = 'New Application';
                }
            }

            if ($fiveApplicationData) {
                if (in_array($application->merchant_id, $fiveApplicationData)) {
                    $applications[$key]['inform_merchant'] = 1;
                }
            }
            $countMerchant = ConsumerApplication::where('merchant_id', $application->merchant_id)->whereIn('state', ['nach registered', 'disbursed', 'closed'])->count();
            if ($countMerchant <= 3) {
                $applications[$key]['first_three_application_received'] = 1;
            }

            /*if($application->purpose){
                $applications[$key]['can_send_to_onefin'] = OneFinService::canSendToOnefin($application->lender_id, $application->purpose);
            }*/

            if($application->lender_id == Utkarsh::$lender_id){
                $applications[$key]['utkarsh_vkyc'] = UtkarshVKYC::where('application_id', $application->id)->where('applicant_type', 1)->orderBy('created_at', 'desc')->first(['id', 'get_vkyc_response']);
                $applications[$key]['utkarsh_vkyc_co'] = UtkarshVKYC::where('application_id', $application->id)->where('applicant_type', 2)->orderBy('created_at', 'desc')->first(['id', 'get_vkyc_response']);
            }
        }

        return $applications;
    }


    public function dateToTimeString($last_seen, $latest_app)
    {
        $date = Carbon::parse($last_seen);

        $monthsRemaining = $date->diffInMonths($latest_app);
        $daysRemaining = $date->diffInDays($latest_app);
        $hoursRemaining = $date->diffInHours($latest_app);
        $minutesRemaining = $date->diffInMinutes($latest_app);
        $secondsRemaining = $date->diffInSeconds($latest_app);

        return ($secondsRemaining <= 59) ? $secondsRemaining . ' sec ago' : ($minutesRemaining <= 59 ? $minutesRemaining . ' min ago' : ($hoursRemaining <= 23 ? $hoursRemaining . ' hour ago' : ($daysRemaining <= Carbon::now()->daysInMonth ? $daysRemaining . ' days ago' : $monthsRemaining . ' months ago')));
    }

    public function getApplicationLenderBank($id)
    {
        $application = ConsumerApplication::with('lender.banks', 'emi', 'application_element','application_element.merchant_center','merchant')->where('id', $id)->first();

        $withheld_percent = LiabilityLog::where('application_id', $id)->orderBy('created_at', 'desc')->first(['liability_percent', 'liability_amount']);

        $request = new Request();
        $net_disbursement = (new DisbursementController($request))->getDisbursementAmount($application);

        $withheld_amount = isset($withheld_percent) ? $withheld_percent->liability_amount : 0;

        $payout = '';


        if($application->merchant_id != 21) {
            $isCenterDisbursement = isset($application->application_element) && isset($application->application_element->merchant_center) ? 1 : 0;

            $bankDisbursal = $application->merchant_bank_details;
            if ($isCenterDisbursement) {
                $bankDisbursalStatus = isset($application->application_element) && isset($application->application_element->merchant_center) && isset($application->application_element->merchant_center->bank_details) && isset($application->application_element->merchant_center->bank_details->account_number) && $application->application_element->merchant_center->bank_details->account_number ? $application->application_element->merchant_center->bank_details : false;
                if ($bankDisbursalStatus) {
                    $bankDisbursal = $bankDisbursalStatus;
                }
            }
        }else{
            $bankDisbursal = Bank::where('application_id', $id)->first(['account_number','ifsc_code','name as account_holder','karza_response']);
            if(isset($bankDisbursal->karza_response) && $bankDisbursal->karza_response) {
                $bank_validation = json_decode($bankDisbursal->karza_response);
                if ((isset($bank_validation->result) && (isset($bank_validation->result->bankTxnStatus) && $bank_validation->result->bankTxnStatus == false) || (isset($bank_validation->result->bankResponse) && $bank_validation->result->bankResponse != 'Transaction Successful')) || !isset($bank_validation->result->bankResponse)) {
                    unset($bankDisbursal);
                }
            }else{
                unset($bankDisbursal);
            }
        }

        if(isset($bankDisbursal->account_number)){
            $payout = '<div class="ac_de_merc" style="display: none;"><div style="color: red;">Please double check account details</div><table class="table"><thead><tr><th>Account Number</th><th>IFSC</th><th>Account Holder</th></tr></thead><tbody><tr><td>'.$bankDisbursal->account_number.'</td><td>'.$bankDisbursal->ifsc_code.'</td><td>'.$bankDisbursal->account_holder.'</td></tr></tbody></table></div>';
        }

        $data = [];
        foreach ($application->lender->banks as $bank) {
            $data[] = ['id' => $bank->id, 'name' => $bank->bank_name];
        }

        return \response()->json(['status' => ($data) ? 'OK' : 'FAIL',
            'data' => $data, 'payout' => $payout, 'withheld_amount' => isset($withheld_amount) && !empty($withheld_amount) ? $withheld_amount : 0,
            'reference_number' => $application->application_element && $application->application_element->reference_number ? $application->application_element->reference_number : '',
            'selected_bank_id' => ($application->application_element && $application->application_element->bank_id) ? $application->application_element->bank_id : 0], 200);
    }

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

        $status = 'OK';
        try {
            if ($request->has('bank_id') && $request->has('application_id')) {
                $data = [
                    'bank_id' => $request->get('bank_id'),
                    'payment_transfer_date' => $request->get('actual_disbursement_date'),
                    'reference_number' => $request->get('reference_number'),
                    'hold_amount' => $request->get('loss_guarantee_withhold_amount'),
                    'is_payout' => $request->has('is_payout_api') && $request->get('is_payout_api') == 1 ? 1 : 0
                    ];

                (new Slack(new Request(['title' => 'Disbursal Log', 'fields' => ['id' => $request->has('application_id'), 'is_payout' => $request->get('is_payout_api') == 1 ? 1 : 0 ], 'group' => Slack::$STAGE_TESTING])))->send();
                if(!empty($request->get('dis_product_name_data'))){
                    $data  =array_merge($data, ['product_name' => $request->get('dis_product_name_data')]);
                }

                ConsumerApplicationElement::where('application_id', $id)->update(
                    $data
                );
            }
        } catch (\Exception $e) {
            $status = 'FAIL';
        }

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

    public function pendingDoc($consumer_applications, $data)
    {
        $document = [];
        $docsRequired = isset($this->pendingDoc[$consumer_applications->state]) ? $this->pendingDoc[$consumer_applications->state] : [];


        $dataLists = $this->getUnapprovedPincodes($consumer_applications);
        if($dataLists['unapproved_pin_codes'] && !isset($dataLists['approver_data_exist']->id)){
            $docsRequired =  array_merge($docsRequired, ['Get Pincode Approval' => 'get_pincode_approval']);
        }


        $blackListData = $this->getBlacklistData($consumer_applications);
        if($blackListData['status'] == true){
            $docsRequired = array_merge($docsRequired,['Blacklisted by RBI'=>'blacklisted_by_rbi']);
        }



        if (isset($docsRequired['Co-applicant Income']) && (isset($data['co_applicant_for_income']) && $data['co_applicant_for_income'] == 0)) {
            unset($docsRequired['Co-applicant Income']);
        }

        if (isset($data['credit_appraisal_memo']) && $data['credit_appraisal_memo']) {
            $docsRequired = array_merge($docsRequired,['Credit Appraisal Memo'=>'credit_appraisal_memo']);
        }

        if (isset($docsRequired['Co-applicant Sign']) && (isset($data['co_applicant_for_signing']) && $data['co_applicant_for_signing'] == 0)) {
            unset($docsRequired['Co-applicant Sign']);
        }

        $listsData = $this->getOtherRequiredDocument($consumer_applications, true);

        $docsRequired = array_merge($docsRequired, array_map(function ($item) {
            return str_replace(' ', '_', $item);
        }, $listsData['sorted']));

        if ($docsRequired) {
            $request = new Request();
            $docsCheck = array_values($docsRequired);
            $request->attributes->add(['check' => $docsCheck, 'data' => ['application' => $consumer_applications, 'getOtherRequiredDocument' => $listsData], 'bot' => true]);
            $docsCheck = $this->checkValidations($request);
            $docsChecked = $docsCheck->getData();

            foreach ($docsRequired as $key => $value) {
                if (isset($docsChecked->$value)) {
                    $document[$key] = $docsChecked->$value;
                }
            }
        }
        if ($document && count(array_unique(array_values($document))) == 1 && isset(array_unique(array_values($document))[0]) && array_unique(array_values($document))[0] && $consumer_applications->state == 'approved') {
            $this->scheduleVerificationCall($consumer_applications->id);
        }

        return ['document' => $document, 'docsRequired' => $listsData['complete']];
    }

    public function scheduleVerificationCall($id)
    {
        $CallLogs = CallLogs::where('_id', $id)->where('id_type', 'application_id')->where('status', 'completed')->where('purpose', 'verification_call')->first(['id']);

        $ConsumerApplicationFiles = ConsumerApplicationFiles::where('consumer_application_id', $id)->where('file_type', 'loan_agreement_esign')->first(['id']);

        if (!isset($ConsumerApplicationFiles->id)) {
            $ConsumerApplicationFiles = ConsumerApplicationFiles::where('consumer_application_id', $id)->where('file_type', 'agreement')->first(['id']);
        }

        if (!isset($CallLogs->id) && isset($ConsumerApplicationFiles->id)) {
            $schedule_verification_call = JobProvider::where('application_id', $id)->where('from', 'schedule_verification_call')->first(['id']);
            if (!isset($schedule_verification_call->id)) {
                $payload[] = [
                    'payload' => json_encode(['id' => $id]),
                    'from' => 'schedule_verification_call',
                    'application_id' => $id,
                    'available_at' => Carbon::now()->addHour(2)->toDateTimeString(),
                    'created_at' => Carbon::now()->toDateTimeString()
                ];

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

    public function getOtherRequiredDocument($consumer_applications, $isComplete = false)
    {
        $lists = [];
        if ($consumer_applications->application_element && $consumer_applications->application_element->mandatory_document_list) {
            $documents = explode(',', $consumer_applications->application_element->mandatory_document_list);
            foreach ($documents as $document) {
                $lists[trim($document)] = trim(ucwords(str_replace('_', ' ', $document)));
            }
        }
        $listsData = $this->getAutoAssignedDocumentsV1($consumer_applications, $lists);
        if (!$isComplete) {
            return $listsData['sorted'];
        }
        return $listsData;
    }

    public function getAutoAssignedDocumentsV1($consumer_applications, $lists)
    {
        $listsBefore = $lists;
        $_docLists['lists'] = array();
        $_docLists['completeList'] = array();


        $files = [];
        if ($consumer_applications->documents) {
            foreach ($consumer_applications->documents as $document) {
                $docKey = strtolower(str_replace(' ', '_', $document->file_type));
                if ($docKey == 'salary_slip') {
                    $files[] = 'pay_slip';
                }
                $files[] = $docKey;
            }
        }


        if ($consumer_applications->application_element && $consumer_applications->application_element->auto_document_rule_id && ($consumer_applications->state == 'approved' || $this->isInternal)) {
            $documentRuleID = $consumer_applications->application_element->auto_document_rule_id;
            $_docLists = (new GradeController(new Request()))->getPreDocumentsList($documentRuleID, $consumer_applications, $files);
        }
        if ($listsBefore) {
            $receivedDocument = (new GradeController(new Request()))->isDocumentReceived(array_values($listsBefore), $files);
            if ($receivedDocument['completeList']) {
                $_docLists['completeList'] = array_merge($_docLists['completeList'], $receivedDocument['completeList']);
            }
            if ($receivedDocument['lists']) {
                $modifyLists = [];
                foreach ($receivedDocument['lists'] as $_listItem) {
                    $modifyLists[trim(ucwords(str_replace('_', ' ', $_listItem)))] = trim(strtolower(str_replace(' ', '_', $_listItem)));
                }
                $_docLists['lists'] = array_merge($_docLists['lists'], $modifyLists);
            }
        }
        return ['sorted' => $_docLists['lists'], 'complete' => array_flip($_docLists['completeList'])];
    }

    public function getAutoAssignedDocuments($consumer_applications, $lists)
    {
        $files = [];
        foreach ($consumer_applications->documents as $document) {
            $files[] = $document->file_type;
        }

        if ($consumer_applications->application_element && $consumer_applications->application_element->auto_document_rule_id && $consumer_applications->state == 'approved') {
            $documentRuleID = $consumer_applications->application_element->auto_document_rule_id;
            $document = DocumentSets::find(DocumentRule::find($documentRuleID)->document_set);
            if ($document) {
                $documentList = json_decode($document->documents);
                foreach ($documentList as $index => $item) {
                    if ($this->isDocumentRequired($item, $documentList, $files)) {
                        $lists[trim(ucwords($item->id))] = trim(str_replace(' ', '_', strtolower($item->id)));
                    }
                }
            }
        }

        return $lists;
    }

    public function isDocumentRequired($item, $documents, $files)
    {
        if ($item->group && $item->mandatory == 'true') {
            $groups = [];
            $_groups = [];
            $__groups = [];
            foreach ($documents as $document) {
                if ($document->group) {
                    $groups[$document->group][] = str_replace(' ', '_', strtolower($document->id));
                    $_groups[$document->group][] = $document->id;
                    $__groups[$document->group][] = $document->optional;
                }
            }
            if ($groups) {
                if ($groups[$item->group]) {
                    if (empty(array_intersect($files, $groups[$item->group]))) {
                        if (!empty(array_intersect($files, $_groups[$item->group])) ? false : true) {
                            if (in_array('false', $__groups[$item->group])) {
                                return true;
                            } else {
                                return false;
                            }
                        } else {
                            return false;
                        }
                    } else {
                        return false;
                    }
                }
            }
        }

        return (!$item->group && $item->mandatory == 'true') ? true : false;
    }

    public function getPastLogs($data)
    {
        $state = isset($data->state) ? $data->state : $data;
        $status = $this->statusreversearray[strtolower($state)];
        array_push($status, $state);
        return $status;
    }

    public function scoreCard($id)
    {
        ini_set('max_execution_time', -1);
        set_time_limit(0);
        ini_set('memory_limit', '-1');

        $consumer_application = ConsumerApplication::with('telecom_data')->where('id', $id)->first(['name','co_applicant_name','mobile_number','created_at','user_id','id']);
        if(!isset($consumer_application->id)){
            \Session::flash('error','Application does not exist');
            return redirect()->to('/admin/consumer-applications');
        }

        $request = new Request();
        $request->attributes->add(['application_id' => $id]);
        $response = $this->getScoreCard($request);
        $i = 0;
        // $consumer_application = ConsumerApplication::with('telecom_data')->where('id', $id)->first(['co_applicant_name','mobile_number','created_at','user_id']);

        $response['manual'] = ConsumerApplicationFiles::where('consumer_application_id', $id)->where('bureau_report_type','!=','')->where('bureau_report_score','!=','')->get(['bureau_report_type','bureau_report_score','applicant_type','file_path','created_at']);

        foreach($response['manual'] as $key => $content){
            if($content->applicant_type == 1){
                $response['manual_applicant_creditscore'] = $content->bureau_report_score;
                $response['manual_applicant_file_path'] = $content->file_path;
            }
            if($content->applicant_type == 2){
                $response['manual_co_applicant_creditscore'] = $content->bureau_report_score;
                $response['manual_co_applicant_file_path'] = $content->file_path;
            }
        }

        $response['auto_creditscore'] = CreditReport::where('application_id',$id)->where('applicant_type',2)->orderBy('created_at','desc')->first(['Score']);
        $response['auto_co_applicant_name'] = $consumer_application->co_applicant_name;
        $response['bureau'] = CreditReport::where('application_id',$id)->orderBy('created_at','desc')->first(['bureau']);
        $telecome_data = TelecomData::where('mobile_number', wall_decrypt($consumer_application->mobile_number))->first(['telecom_response']);
        if (isset($response['bureauInput'][0])) {
            $latestdpd = $this->getDPD($id);
            foreach ($response['bureauInput'] as $bureauInput) {
                if($response['bureau']->bureau == "experian"){
                    if (isset($latestdpd[$bureauInput['type_of_loan']][date('Y-m-d', strtotime($bureauInput['date_opened']))][$bureauInput['loan_sanctioned']]['six_mon'])) {
                        $response['bureauInput'][$i]['sixmonth'] = $latestdpd[$bureauInput['type_of_loan']][date('Y-m-d', strtotime($bureauInput['date_opened']))][$bureauInput['loan_sanctioned']]['six_mon'];
                    } else {
                        $response['bureauInput'][$i]['sixmonth'] = '-';
                    }
                    if (isset($latestdpd[$bureauInput['type_of_loan']][date('Y-m-d', strtotime($bureauInput['date_opened']))][$bureauInput['loan_sanctioned']]['twelve_mon'])) {
                        $response['bureauInput'][$i]['twelvemonth'] = $latestdpd[$bureauInput['type_of_loan']][date('Y-m-d', strtotime($bureauInput['date_opened']))][$bureauInput['loan_sanctioned']]['twelve_mon'];
                    } else {
                        $response['bureauInput'][$i]['twelvemonth'] = '-';
                    }

                }else{

                    if (isset($latestdpd[$bureauInput['type_of_loan']][date('Y-m-d', strtotime($bureauInput['date_opened']))][$bureauInput['loan_sanctioned']]['six']['dpd'])) {
                        $response['bureauInput'][$i]['sixmonth'] = $latestdpd[$bureauInput['type_of_loan']][date('Y-m-d', strtotime($bureauInput['date_opened']))][$bureauInput['loan_sanctioned']]['six']['dpd'];
                    } else {
                        $response['bureauInput'][$i]['sixmonth'] = '-';
                    }
                    if (isset($latestdpd[$bureauInput['type_of_loan']][date('Y-m-d', strtotime($bureauInput['date_opened']))][$bureauInput['loan_sanctioned']]['twelve']['dpd'])) {
                        $response['bureauInput'][$i]['twelvemonth'] = $latestdpd[$bureauInput['type_of_loan']][date('Y-m-d', strtotime($bureauInput['date_opened']))][$bureauInput['loan_sanctioned']]['twelve']['dpd'];
                    } else {
                        $response['bureauInput'][$i]['twelvemonth'] = '-';
                    }
                }
                if (isset($latestdpd[$bureauInput['type_of_loan']][date('Y-m-d', strtotime($bureauInput['date_opened']))][$bureauInput['loan_sanctioned']]['AccountStatus'])) {
                    $response['bureauInput'][$i]['AccountStatus'] = $latestdpd[$bureauInput['type_of_loan']][date('Y-m-d', strtotime($bureauInput['date_opened']))][$bureauInput['loan_sanctioned']]['AccountStatus'];
                } else {
                    $response['bureauInput'][$i]['AccountStatus'] = '';
                }
                if (isset($latestdpd[$bureauInput['type_of_loan']][date('Y-m-d', strtotime($bureauInput['date_opened']))][$bureauInput['loan_sanctioned']]['PrincipalWriteOff'])) {
                    $response['bureauInput'][$i]['PrincipalWriteOff'] = $latestdpd[$bureauInput['type_of_loan']][date('Y-m-d', strtotime($bureauInput['date_opened']))][$bureauInput['loan_sanctioned']]['PrincipalWriteOff'];
                } else {
                    $response['bureauInput'][$i]['PrincipalWriteOff'] = '';
                }
                if (isset($latestdpd['enquiries'])) {
                    $response['Enquiries'] = $latestdpd['enquiries'];
                } else {
                    $response['Enquiries'] = null;
                }
                $i++;
            }
        }
        $i = 0;
        if (isset($response['bureauInputCoApplicant'][0])) {
            $latestdpd = $this->getDPD($id, 2);
            foreach ($response['bureauInputCoApplicant'] as $bureauInputCo) {
                if($response['bureau']->bureau == "experian"){
                    if (isset($latestdpd[$bureauInputCo['type_of_loan']][date('Y-m-d', strtotime($bureauInputCo['date_opened']))][$bureauInputCo['loan_sanctioned']]['six_mon'])) {
                        $response['bureauInputCoApplicant'][$i]['sixmonth'] = $latestdpd[$bureauInputCo['type_of_loan']][date('Y-m-d', strtotime($bureauInputCo['date_opened']))][$bureauInputCo['loan_sanctioned']]['six_mon'];
                    } else {
                        $response['bureauInputCoApplicant'][$i]['sixmonth'] = '-';
                    }
                    if (isset($latestdpd[$bureauInputCo['type_of_loan']][date('Y-m-d', strtotime($bureauInputCo['date_opened']))][$bureauInputCo['loan_sanctioned']]['twelve_mon'])) {
                        $response['bureauInputCoApplicant'][$i]['twelvemonth'] = $latestdpd[$bureauInputCo['type_of_loan']][date('Y-m-d', strtotime($bureauInputCo['date_opened']))][$bureauInputCo['loan_sanctioned']]['twelve_mon'];
                    } else {
                        $response['bureauInputCoApplicant'][$i]['twelvemonth'] = '-';
                    }

                }else{

                    if (isset($latestdpd[$bureauInputCo['type_of_loan']][date('Y-m-d', strtotime($bureauInputCo['date_opened']))][$bureauInputCo['loan_sanctioned']]['six']['dpd'])) {
                        $response['bureauInputCoApplicant'][$i]['sixmonth'] = $latestdpd[$bureauInputCo['type_of_loan']][date('Y-m-d', strtotime($bureauInputCo['date_opened']))][$bureauInputCo['loan_sanctioned']]['six']['dpd'];
                    } else {
                        $response['bureauInputCoApplicant'][$i]['sixmonth'] = '-';
                    }
                    if (isset($latestdpd[$bureauInputCo['type_of_loan']][date('Y-m-d', strtotime($bureauInputCo['date_opened']))][$bureauInputCo['loan_sanctioned']]['twelve']['dpd'])) {
                        $response['bureauInputCoApplicant'][$i]['twelvemonth'] = $latestdpd[$bureauInputCo['type_of_loan']][date('Y-m-d', strtotime($bureauInputCo['date_opened']))][$bureauInputCo['loan_sanctioned']]['twelve']['dpd'];
                    } else {
                        $response['bureauInputCoApplicant'][$i]['twelvemonth'] = '-';
                    }
                }

                if (isset($latestdpd[$bureauInputCo['type_of_loan']][date('Y-m-d', strtotime($bureauInputCo['date_opened']))][$bureauInputCo['loan_sanctioned']]['AccountStatus'])) {
                    $response['bureauInputCoApplicant'][$i]['AccountStatus'] = $latestdpd[$bureauInputCo['type_of_loan']][date('Y-m-d', strtotime($bureauInputCo['date_opened']))][$bureauInputCo['loan_sanctioned']]['AccountStatus'];
                } else {
                    $response['bureauInputCoApplicant'][$i]['AccountStatus'] = '';
                }
                if (isset($latestdpd[$bureauInputCo['type_of_loan']][date('Y-m-d', strtotime($bureauInputCo['date_opened']))][$bureauInputCo['loan_sanctioned']]['PrincipalWriteOff'])) {
                    $response['bureauInputCoApplicant'][$i]['PrincipalWriteOff'] = $latestdpd[$bureauInputCo['type_of_loan']][date('Y-m-d', strtotime($bureauInputCo['date_opened']))][$bureauInputCo['loan_sanctioned']]['PrincipalWriteOff'];
                } else {
                    $response['bureauInputCoApplicant'][$i]['PrincipalWriteOff'] = '';
                }
                if (isset($latestdpd['enquiries'])) {
                    $response['Co_Enquiries'] = $latestdpd['enquiries'];
                } else {
                    $response['Co_Enquiries'] = null;
                }
                $i++;
            }
        }

        $i = 0;
        $guarantorLoans = FOIR::where('application_id', $id)->where('OwnershipType', 'like', '%Guarantor%')->get();
        if(!empty($guarantorLoans)){
            $latestdpd = $this->getDPD($id);
            foreach ($guarantorLoans as $loan) {
                if($response['bureau']->bureau == "experian"){
                    if (isset($latestdpd[$loan['AccountType']][date('Y-m-d', strtotime($loan['DateOpened']))][$loan['ApprovedAmount']]['six_mon'])) {
                        $guarantorLoans[$i]['sixmonth'] = $latestdpd[$loan['AccountType']][date('Y-m-d', strtotime($loan['DateOpened']))][$loan['ApprovedAmount']]['six_mon'];
                    } else {
                        $guarantorLoans[$i]['sixmonth'] = 0;
                    }
                    if (isset($latestdpd[$loan['AccountType']][date('Y-m-d', strtotime($loan['DateOpened']))][$loan['ApprovedAmount']]['twelve_mon'])) {
                        $guarantorLoans[$i]['twelvemonth'] = $latestdpd[$loan['AccountType']][date('Y-m-d', strtotime($loan['DateOpened']))][$loan['ApprovedAmount']]['twelve_mon'];
                    } else {
                        $guarantorLoans[$i]['twelvemonth'] = 0;
                    }

                }else{

                if (isset($latestdpd[$loan['AccountType']][date('Y-m-d', strtotime($loan['DateOpened']))][$loan['ApprovedAmount']]['six']['dpd'])) {
                    $guarantorLoans[$i]['sixmonth'] = $latestdpd[$loan['AccountType']][date('Y-m-d', strtotime($loan['DateOpened']))][$loan['ApprovedAmount']]['six']['dpd'];
                } else {
                    $guarantorLoans[$i]['sixmonth'] = 0;
                }
                if (isset($latestdpd[$loan['AccountType']][date('Y-m-d', strtotime($loan['DateOpened']))][$loan['ApprovedAmount']]['twelve']['dpd'])) {
                    $guarantorLoans[$i]['twelvemonth'] = $latestdpd[$loan['AccountType']][date('Y-m-d', strtotime($loan['DateOpened']))][$loan['ApprovedAmount']]['twelve']['dpd'];
                } else {
                    $guarantorLoans[$i]['twelvemonth'] = 0;
                }
            }
                if (isset($latestdpd[$loan['AccountType']][date('Y-m-d', strtotime($loan['DateOpened']))][$loan['ApprovedAmount']]['AccountStatus'])) {
                    $guarantorLoans[$i]['AccountStatus'] = $latestdpd[$loan['AccountType']][date('Y-m-d', strtotime($loan['DateOpened']))][$loan['ApprovedAmount']]['AccountStatus'];
                } else {
                    $guarantorLoans[$i]['AccountStatus'] = '';
                }
                if (isset($latestdpd[$loan['AccountType']][date('Y-m-d', strtotime($loan['DateOpened']))][$loan['ApprovedAmount']]['PrincipalWriteOff'])) {
                    $guarantorLoans[$i]['PrincipalWriteOff'] = $latestdpd[$loan['AccountType']][date('Y-m-d', strtotime($loan['DateOpened']))][$loan['ApprovedAmount']]['PrincipalWriteOff'];
                } else {
                    $guarantorLoans[$i]['PrincipalWriteOff'] = '';
                }
                $i++;
            }
        }

        $response['guarantor_loans'] = !empty($guarantorLoans) ?  $guarantorLoans : '';
        $response['telecom_response'] = (isset($telecome_data->telecom_response)) ? json_decode(json_decode(wall_decrypt($telecome_data->telecom_response))) : '';
        $fraud_report = $this->getFraudReports($id);
        $response['fraud_report'] = isset($fraud_report[0]) ? $fraud_report[0] : '';
        $response['fraud_report_data'] = isset($fraud_report[1]) ? $fraud_report[1] : '';
        $response['fraud_report_coapplicants'] = isset($fraud_report[2]) ? $fraud_report[2] : '';
        $response['finbit_data'] = FinBitData::with('consumer_application','consumer_application_file')->where('application_id', $id)->get();

        $s3 = Storage::disk('s3');
        $files = ConsumerApplicationFiles::where('consumer_application_id', $id)
            ->where('file_type', 'pirimid_analysis_json')
            ->where('doc_ref_id', '!=', '')
            ->orderBy('updated_at', 'asc')
            ->get(['applicant_type', 'file_path', 'updated_at']);

        $dataApplicant = [];
        $dataCoApplicant = [];

        // Process Applicant Files Data
        foreach ($files->where('applicant_type', 1) as $applicantFile) {
            if ($s3->exists($applicantFile->file_path)) {
                $data = $s3->get($applicantFile->file_path);
                $decoded_data = json_decode($data, true);
                
                $timestampString = $applicantFile->updated_at->toDateTimeString();
                $dataApplicant[$timestampString] = $this->processPirimidData($decoded_data, $timestampString);   
            }
        }

        // Process Co-Applicant Files Data
        foreach ($files->where('applicant_type', 2) as $coApplicantFile) {
            if ($s3->exists($coApplicantFile->file_path)) {
                $data = $s3->get($coApplicantFile->file_path);
                $decoded_data = json_decode($data, true);
                
                $timestampString = $coApplicantFile->updated_at->toDateTimeString();
                $dataCoApplicant[$timestampString] = $this->processPirimidData($decoded_data, $timestampString);
            }
        }

        $response['cumulativeApplicant'] = $this->calculateCumulativeAnalysis($dataApplicant);
        $response['cumulativeCoApplicant'] = $this->calculateCumulativeAnalysis($dataCoApplicant);

        $response['dataApplicant'] = $dataApplicant;
        $response['dataCoApplicant'] = $dataCoApplicant;

        $response['applicantName'] = $consumer_application->name;

        try {
            $response['bounce_charges'] = BounceTransactions::where('application_id', $id)->get();
            $response['login_date'] = Carbon::createFromFormat('Y-m-d', explode(' ', $consumer_application->created_at)[0])->subMonth(3)->startOfDay()->toDateTimeString();
            $response['epfReport'] = (new EPFUANLookup())->getUANByApplication($id, true);
            if (isset($response['error']) && isset($response['error']['error'])) {
                Session::flash('error', $response['error']['error']);
            }
        }catch (\Exception $e){
            (new Slack(new Request(['title'=>'ScoreCard Error','fields'=>['Application ID'=>$id,'error'=>$e->getMessage(),'line'=>$e->getLine(),'trace'=>$e->getTraceAsString()], 'group' => Slack::$STAGE_TESTING])))->send();
        }

        return view('admin.consumer-application.scorecard.index', $response);
    }

    private function processPirimidData(?array $pirimid_data, string $timestamp): array{
        if (empty($pirimid_data['analytics']['accountProfiles'])) {
            return ['overall' => [], 'accounts' => []];
        }

        $processedAccounts = [];
        $accountProfiles = $pirimid_data['analytics']['accountProfiles'] ?? [];

        $fileMinStartDate = null;
        $fileMaxEndDate = null;

        foreach ($accountProfiles as $index => $profile) {
            $linkedAccRef = $profile['Account']['linkedAccRef'] ?? null;
            if (!$linkedAccRef) {
                continue; // Skip if the profile has no reference ID
            }

            $startDate = $profile['summary']['transactionStartDate'] ?? null;
            $endDate = $profile['summary']['transactionEndDate'] ?? null;

            try {
                $startDt = $startDate ? new \DateTime($startDate) : null;
                $endDt = $endDate ? new \DateTime($endDate) : null;

                if ($startDt && (is_null($fileMinStartDate) || $startDt < $fileMinStartDate)) {
                    $fileMinStartDate = $startDt;
                }
                if ($endDt && (is_null($fileMaxEndDate) || $endDt > $fileMaxEndDate)) {
                    $fileMaxEndDate = $endDt;
                }
            } catch (Exception $e) {
                // Ignore invalid date formats
            }

            $processedAccounts[$linkedAccRef] = [
                'name'                  => $profile['Holders']['Holder'][0]['name'] ?? '',
                'accountNumber'         => $profile['Account']['number'] ?? '',
                'bankName'              => $profile['Account']['bank'] ?? '',
                'accountType'           => $profile['Account']['acctype'] ?? '',
                'linkedAccRef'          => $linkedAccRef,
                'startDate'             => $startDate,
                'endDate'               => $endDate,
                
                // Correlating with the index of the account profile
                'avgBalance'            => $pirimid_data['analytics']['accountWiseAnalysis'][$index]['avgEodBalance'] ?? 0,
                'adjustedAvgBalance'    => $pirimid_data['analytics']['accountWiseAnalysis'][$index]['customAbbs']['adjustedAbb2']['averageOfMonthlyAverages'] ?? 0,
                'noOfEmiBounces'        => $pirimid_data['analytics']['bounceAnalysis']['accountWiseBounceAnalytics'][$index]['totalEmiBounceTxn'] ?? 0,
                'inwardChequeBounce'    => $pirimid_data['analytics']['bounceAnalysis']['accountWiseBounceAnalytics'][$index]['totalIWChqBounceTxns'] ?? 0,
                'outwardChequeBounce'   => $pirimid_data['analytics']['bounceAnalysis']['accountWiseBounceAnalytics'][$index]['totalOWChqBounceTxns'] ?? 0,
                'bounceTransactions'    => $pirimid_data['analytics']['bounceAnalysis']['accountWiseBounceAnalytics'][$index]['bouncedTransactions'] ?? [],
                'salaryList'            => $pirimid_data['analytics']['frequentCredits']['salaryAnalysis']['accountWise'][$index]['salaryList'] ?? [],
                
                // These might be overall, but let's keep them per account for consistency
                'avgMonthlyEmi'         => $pirimid_data['analytics']['overallEmiAnalytics']['averageMonthlyEmiAmount'] ?? 0,
                'fcuIndicatorTransactions' => $pirimid_data['analytics']['fcuIndicators']['fcuIndicatorTransactions'] ?? [],

                // Initialize speculative trade counters for this specific account
                'speculativeTradeCount' => 0,
                'speculativeTradeAmount' => 0,
                'timestamp'             => $timestamp
            ];
        }

        // Step 2: Loop through all transactions to calculate speculative trades for each account.
        $allTransactions = $pirimid_data['analytics']['allTransactions'] ?? [];

        $bounceCategories = [
                "Bounced I/W ECS Charges",
                "I/W Cheque Bounce Charge",
                "O/W Cheque Bounce Charge",
                "Bounce Charge"
            ];
        $additionalOverallBounces = [];

        foreach ($allTransactions as $transaction) {
            $transactionRef = $transaction['linkedAccRef'] ?? null;
            $category = $transaction['category'] ?? '';

            // Check if the transaction belongs to an account we are processing
            if (isset($processedAccounts[$transactionRef]) && in_array($category, ["Gambling & Betting", "Gaming"])) {
                $processedAccounts[$transactionRef]['speculativeTradeCount']++;
                $processedAccounts[$transactionRef]['speculativeTradeAmount'] += $transaction['amount'] ?? 0;
            }

            if (in_array($category, $bounceCategories)) {
                $additionalOverallBounces[] = $transaction;
            }
        }

            $totalSpeculativeCount = 0;
            $totalSpeculativeAmount = 0;
            foreach($processedAccounts as $account) {
                $totalSpeculativeCount += $account['speculativeTradeCount'];
                $totalSpeculativeAmount += $account['speculativeTradeAmount'];
            }
            
            $overallData = [
                'startDate'             => $fileMinStartDate ? $fileMinStartDate->format('Y-m-d') : null,
                'endDate'               => $fileMaxEndDate ? $fileMaxEndDate->format('Y-m-d') : null,
                'avgMonthlyEmi'         => $pirimid_data['analytics']['overallEmiAnalytics']['averageMonthlyEmiAmount'] ?? 0,
                'avgBalance'            => $pirimid_data['analytics']['overallAnalysis']['avgEodBalance'] ?? 0,
                'adjustedAvgBalance'    => $pirimid_data['analytics']['overallAnalysis']['customAbbs']['adjustedAbb2']['averageOfMonthlyAverages'] ?? 0,
                'noOfEmiBounces'        => $pirimid_data['analytics']['bounceAnalysis']['overAllBounceAnalytics']['totalEmiBounceTxn'] ?? 0,
                'inwardChequeBounce'    => $pirimid_data['analytics']['bounceAnalysis']['overAllBounceAnalytics']['totalIWChqBounceTxns'] ?? 0,
                'outwardChequeBounce'   => $pirimid_data['analytics']['bounceAnalysis']['overAllBounceAnalytics']['totalOWChqBounceTxns'] ?? 0,
                'fcuIndicatorTransactions' => $pirimid_data['analytics']['fcuIndicators']['fcuIndicatorTransactions'] ?? [],
                'bounceTransactions'    => array_merge($pirimid_data['analytics']['bounceAnalysis']['overAllBounceAnalytics']['bouncedTransactions'] ?? [],$additionalOverallBounces),
                'speculativeTradeCount' => $totalSpeculativeCount,
                'speculativeTradeAmount' => $totalSpeculativeAmount,
                'timestamp'             => $timestamp,
                'salaryList'     => $pirimid_data['analytics']['frequentCredits']['salaryAnalysis']['overall']['salaryList'] ?? [],

            ];

            // PART C: Return the new combined structure
            return [
                'overall' => $overallData,
                'accounts' => array_values($processedAccounts)
            ];
    }

    private function calculateCumulativeAnalysis(array $timestampedData): array
    {
        // Initialize a template for our final summary with all values at zero.
        $cumulative = [
            'avgBalance'            => 0,
            'adjustedAvgBalance'    => 0,
            'noOfEmiBounces'        => 0,
            'inwardChequeBounce'    => 0,
            'outwardChequeBounce'   => 0,
            'avgMonthlyEmi'         => 0,
            'speculativeTradeCount' => 0,
            'speculativeTradeAmount' => 0,
            'startDate'             => null, 
            'endDate'               => null,
        ];

        $fileCount = count($timestampedData);

        // If there are no files to process, return the empty template.
        if ($fileCount === 0) {
            $cumulative['startDate'] = null;
            $cumulative['endDate'] = null;
            return $cumulative;
        }

        // Loop through the data from each processed file.
        foreach ($timestampedData as $dataGroup) {
            $overall = $dataGroup['overall'];

            try {
                $fileStartDate = $overall['startDate'] ? new \DateTime($overall['startDate']) : null;
                $fileEndDate = $overall['endDate'] ? new \DateTime($overall['endDate']) : null;

                if ($fileStartDate && (is_null($cumulative['startDate']) || $fileStartDate < $cumulative['startDate'])) {
                    $cumulative['startDate'] = $fileStartDate;
                }
                if ($fileEndDate && (is_null($cumulative['endDate']) || $fileEndDate > $cumulative['endDate'])) {
                    $cumulative['endDate'] = $fileEndDate;
                }
            } catch (Exception $e) {
            }

            $cumulative['noOfEmiBounces']        += $overall['noOfEmiBounces'] ?? 0;
            $cumulative['inwardChequeBounce']    += $overall['inwardChequeBounce'] ?? 0;
            $cumulative['outwardChequeBounce']   += $overall['outwardChequeBounce'] ?? 0;
            $cumulative['speculativeTradeCount'] += $overall['speculativeTradeCount'] ?? 0;
            $cumulative['speculativeTradeAmount']+= $overall['speculativeTradeAmount'] ?? 0;
            $cumulative['avgBalance']            += $overall['avgBalance'] ?? 0; // Assuming avgBalance is present in overall
            $cumulative['adjustedAvgBalance']    += $overall['adjustedAvgBalance'] ?? 0; // Assuming this is present
            $cumulative['avgMonthlyEmi']         += $overall['avgMonthlyEmi'] ?? 0;
        }

        $cumulative['startDate'] = $cumulative['startDate'] ? $cumulative['startDate']->format('Y-m-d') : null;
        $cumulative['endDate'] = $cumulative['endDate'] ? $cumulative['endDate']->format('Y-m-d') : null;

        return $cumulative;
    }

    private function groupAccountsByTimestamp(array $accounts): array
    {
        $grouped = [];
        foreach ($accounts as $account) {
            // Use the timestamp as the key and push the account into a sub-array
            $grouped[$account['timestamp']][] = $account;
        }
        return $grouped;
    }

    public function getUserFormattedData($user_id, $checkDate = null){
        try{
            $user = new UserController();
            if($appFiles = $user->getAppFileSummaryV1($user_id, $checkDate)){
                return $user->getResolvedAppData($appFiles);
            }
        }catch (\Exception $e){
            (new Slack(new Request(['title'=>'Error catching user data','fields'=>['User ID'=>$user_id,'error'=>$e->getMessage(),'line'=>$e->getLine(),'trace'=>$e->getTraceAsString()], 'group' => Slack::$STAGE_TESTING])))->send();
        }

        return false;
    }

    public function isFraud($id, $name, $isData = false, $returnBoth = false)
    {
        $status = false;
        try {
            $s3 = Storage::disk('s3');
            $filePath = $id . '/' . $name;
            if(!$s3->exists($filePath)){
                $files = ConsumerApplicationFiles::where('consumer_application_id', $id)->whereNotNull('accountUID')->orderBy('created_at','desc')->get(['id','accountUID']);
                foreach($files as $file) {
                    if ($file->accountUID && $s3->exists($id . '/' . $file->accountUID . '/' . $name)) {
                        $filePath = $id . '/' . $file->accountUID . '/' . $name;
                        break;
                    }
                }
            }
            $data = $s3->get($filePath);
            if($isData){
                return json_decode($data, 1);
            }
            $fraud_report = json_decode($data);
            foreach ($fraud_report->result as $item) {
                if (($item->rule == 'SUSPICIOUS_FILE_INPUT' || $item->rule == 'CREATED_AND_MODIFIED_DATE_MISMATCH') && $item->status == 'FAIL') {
                    $status = true;
                }
            }
        } catch (\Exception $e) {

        }
        if($returnBoth && isset($data)){
            return [$status, json_decode($data, 1)];
        } else{
            return $status;
        }
    }


    public function getFraudReports($id)
    {

        try {
            $fraud_reports = [];
            $fraud_reports_coapplicians = [];
            $s3 = Storage::disk('s3');
            $name = 'fraud_report.json';
            $status = false;
            $isPathNormal = false;
            $files = ConsumerApplicationFiles::where('consumer_application_id', $id)->where(function ($query) {
                $query->where('file_type', 'like', '%fraud_report_%')
                ->orWhere('file_type', 'like', '%bank_statement%')
                ->orWhere('file_type', 'like', '%_Excel_File_%');
            })->whereNotNull('accountUID')->orderBy('created_at','desc')->get(['id','accountUID','file_type','applicant_type']);

            foreach($files as $file) {
                if($isPathNormal){
                    //break;
                }
                $path = null;
                if($file->accountUID) {
                    $UID = str_replace('"', '', $file->accountUID);
                    if ($s3->exists($id . '/' . $UID . '/' . $name)) {
                        $path = $id . '/' . $UID . '/' . $name;
                    } else if ($s3->exists($id . '/' . $name) && !$isPathNormal) {
                        $path = $id . '/' . $name;
                        $isPathNormal = true;
                    }

                    if (isset($path) && $path) {
                        $data = $s3->get($path);
                        if ($data) {
                            $fraud_report = json_decode($data);
                            if(isset($fraud_report->result) && isset($fraud_report->result[0]->rule)) {
                                if ($file['applicant_type'] == 1) {
                                    $fraud_reports[] = ['name' => $file->file_type, 'report' => $fraud_report];
                                }else {
                                    $fraud_reports_coapplicians[] = ['name' => $file->file_type, 'report' => $fraud_report];
                                }

                                foreach ($fraud_report->result as $item) {
                                    if (($item->rule == 'SUSPICIOUS_FILE_INPUT' || $item->rule == 'CREATED_AND_MODIFIED_DATE_MISMATCH') && $item->status == 'FAIL') {
                                        $status = true;
                                    }
                                }
                            }
                        }
                    }
                }
            }

        } catch (\Exception $e) {
            echo 'Exception occurred';
            return false;
        }

        return [$status, $fraud_reports, $fraud_reports_coapplicians];
    }

    public function userCreation($application, $skipped = true, Request $request = null){
        try {


            if($request && $request->has('leadData')){
                $application = (object) $request->get('leadData');
            }

            $existingUser = User::where('mobile_number', $application->mobile_number)->first(['id']);

            if ((!isset($existingUser->id)) && !empty($application->email)) {
                $existingUser = User::where('email', $application->email)->first(['id']);
            }

            if (!isset($existingUser->id)) {
                $userSave = new User();
                $userSave->fill([
                    'name' => $application->name,
                    'email' => $application->email,
                    'mobile_number' => $application->mobile_number,
                    'gender' => isset($application->gender) ? strtolower($application->gender) : null,
                    'code' => (new MerchantController())->getReferralCode(),
                    'user_type' => 1,
                    'user_verified' => $skipped ? 0 : 1,
                ]);

                $userSave->save();
                return $userSave->id;
            }else{
                return $existingUser->id;
            }
        }catch (\Exception $e){

        }
    }


    public function assignPTPDate(Request $request){
        $PTP = new PromiseToPay();
        $PTP->fill($request->input());
        $PTP->date = Carbon::createFromFormat('d/m/Y', $request->get('date'))->toDateString();
        $PTP->created_at = Carbon::now()->toDateTimeString();
        $PTP->save();

        if ($request->has('bot'))
            return true;

        if(isset($PTP->id)){

            $promiseToPay = PromiseToPay::with('user')->where('application_id', $request->get('application_id'))->get();

            $table = '<tr style="background-color:#c5c5ff"><td>'.$PTP->date.'</td><td>'.$request->get('name').'</td><td>No Yet</td><td>Awaiting</td><td><i data-id="'.$PTP->id.'" class="delete-ptp-ent fa fa-trash"></i></td></tr>';
            return \response(['status' => 'OK', 'message' => 'PTP Date Assigned successfully', 'data' => $table, 'lists' => ['ptp' => ['lists' => $promiseToPay], 'color' => 'red']]);
        }

        return \response(['status' => 'FAIL', 'message' => 'Failed to assigned PTP Date']);
    }

    public function create($lead = false, $is_bnpl = false)
    {

        if (!Auth::user()->app_create_access && !$lead) {
            Session::flash('error', 'You don\'t have permission to access the page');
            return \redirect()->to('/admin');
        }

        if($is_bnpl && !\Illuminate\Support\Facades\Session::has('BNPL_Applications_Create|2-8-1')){
            return false;
        }
        $selected_categories = explode(',', Auth::user()->category);
        $data['sidebar'] = 'consumer-applications';
        // $data['users']             = User::all();

        $auth_merchant_id = null;
        if(Auth::check() && Auth::user()->merchant_id){
            $auth_merchant_id = Auth::user()->merchant_id;
        }

        $bnpl_merchants = BNPL::getMerchants();
        if($is_bnpl){
            $data['merchants'] = Merchant::where('status', 'active')->where('is_guest_active', 1)->whereIn('id', $bnpl_merchants);
            if($auth_merchant_id){
                $data['merchants'] = $data['merchants']->where('id', $auth_merchant_id);
            }
            $data['merchants'] = $data['merchants']->get();
        }else{
            if(count(array_filter($selected_categories))){
                $data['merchants'] = Merchant::where('status', 'active')->where('is_guest_active', 1)->whereNotIn('id', $bnpl_merchants)->whereIn('category_id', $selected_categories)->where('receive_application', 1);
                if($auth_merchant_id){
                    $data['merchants'] = $data['merchants']->where('id', $auth_merchant_id);
                }
                $data['merchants'] = $data['merchants']->get();
            }else{
                $data['merchants'] = Merchant::where('status', 'active')->where('is_guest_active', 1)->whereNotIn('id', $bnpl_merchants)->where('receive_application', 1);
                if($auth_merchant_id){
                    $data['merchants'] = $data['merchants']->where('id', $auth_merchant_id);
                }
                $data['merchants'] = $data['merchants']->get();
            }
        }
        if(count(array_filter($selected_categories))){
            $data['merchant_category'] = MerchantCategory::whereIn('id', $selected_categories)->get(['name', 'id']);
        }else{
            $data['merchant_category'] = MerchantCategory::where('status', 1)->get(['name', 'id']);
        }
        $data['merchant_location'] = MerchantLocation::get();
        $data['application_status'] = array_map('ucfirst', array_keys($this->arraygroup));

        //default nach properties
        $c = (new ConsumerApplication())->fillable;
        $d = new \stdClass();
        foreach ($c as $item) {
            $d->$item = '';
        }
        $d->id = 0;
        $d->emi = new \stdClass();
        $d->status_logs = new \stdClass();
        $d->created_at = Carbon::now()->toDateTimeString();
        $data['consumer_applications'] = $d;
        /*$data['consumer_applications']->mandateMany = [];
        $nach = (new Nach(new Request()))->getDefaultNachProperties($data['consumer_applications'], 0);
        if(count($data['consumer_applications']->mandateMany) < 2){
            $data['consumer_applications']->mandateMany = $nach;
        }*/
        $data['current_merchant'] = null;
        $data['page_type'] = 'create';
        $data['state_list'] = StateModel::get(['name', 'code', 'id']);

        $data['industries'] = ScoreCard::$industryCreditFair;
        $data['profession'] = ScoreCard::$professionTypeCreditFair;
        $data['negativeProfile'] = NegativeProfile::get();
        $data['disable_edits'] = 1;
        $data['is_pin_set'] = 1;
        $data['lenderAccess'] = $this->getLenderPermissions();
        $data['service_provider_list'] = $this->serviceProviderList();
        $data['inverter_list'] = $this->inverterList();
        $data['panel_list'] = $this->panelList();
        // $data['isCheckboxRequired'] = true;

        if($lead || $is_bnpl){
            return $data;
        }else{
            return view('admin.consumer-application.edit_v1', $data);
        }
    }

    public function inverterList(){
        return ['TATA Power Solar','Waaree','Mundra Solar PV (Adani Solar)','Renewsys India','Emmvee PV Power','Premier Energies','Pixon Green Energy','Websol Energy','Havells','Solarium','Navitas Solar','Jakson Engineers Ltd','M/s Sova Solar Ltd','Pixon Green Energy','Websol Energy Systems','Alpex Solar Pvt. Ltd','M/s Novus Green Energy','PV Power Technologies', 'M/s Rayzon Green', 'M/s Kosol Energies Pvt.','Gautam Solar Pvt. Ltd','M/s Australian Premium Solar','Topsun Energy Ltd','Navitas Green Solutions','Livguard','Polycab','Enphase','Goodwe', 'Growatt', 'Sofar', 'Fronius', 'UTL', 'Luminous', 'V-guard', 'Microtek', 'Loom Solar', 'Waaree Energies', 'Exide', 'Sungrow', 'ZunSolar', 'Vsole Solar', 'Deye', 'KSolare', 'Feston', 'Solis', 'Other'];
    }

    public function panelList(){
        return ['TATA Power Solar','Waaree','Mundra Solar PV (Adani Solar)','Renewsys India','Emmvee PV Power','Premier Energies','Pixon Green Energy','Websol Energy','Havells','Solarium','Navitas Solar','Jakson Engineers Ltd','M/s Sova Solar Ltd','Pixon Green Energy','Websol Energy Systems','Alpex Solar Pvt. Ltd','M/s Novus Green Energy','PV Power Technologies', 'M/s Rayzon Green', 'M/s Kosol Energies Pvt.','Gautam Solar Pvt. Ltd','M/s Australian Premium Solar','Topsun Energy Ltd','Navitas Green Solutions','Livguard','Polycab','Enphase','Goodwe', 'Growatt', 'Sofar', 'Fronius', 'UTL', 'Luminous', 'V-guard', 'Microtek', 'Loom Solar', 'Waaree Energies', 'Exide', 'Saatvik', 'Adani', 'ZunSolar', 'Intersolar', 'Senza', 'Ultima', 'Renew Power Private Limited', 'Loom solar', 'JAKSON BIFACIAL', 'Other'];
    }

    public function serviceProviderList(){
        return ['Southern Power Distribution Company of Andhra Pradesh Limited', 'Eastern Power Distribution Company of Andhra Pradesh Limited', 'Assam Power Distribution Company Limited', 'North Bihar Power Distribution Company Limited', 'South Bihar Power Distribution Company Limited', 'Calcutta Electric Supply Corporation Limited', 'Chandigarh Electricity Department', 'Chhattisgarh State Power Distribution Company Limited', 'Daman and Diu Electricity Department', 'Tata Power Delhi Distribution', 'BSES Yamuna Power Ltd / BSES Rajdhani Power Ltd', 'Goa Electricity- for Tisvadi, Ponda & Verna', 'Goa Electricity- for others', 'Uttar Gujarat VIJ Company Ltd.', 'Pashchim Gujarat VIJ Company Ltd.', 'Madhya Gujarat VIJ Company Limited', 'Dakshin Gujarat VIJ Company Limited', 'Torrent Power Limited - Ahmedabad', 'Torrent Power Limited - Surat', 'Torrent Power Limited - Agra', 'Torrent Power Limited - Bhiwandi', 'Torrent Power Limited - Dahej', 'Dakshin Haryana Bijli Vitran Nigam', 'Uttar Haryana Bijli Vitran Nigam', 'Himachal Pradesh State Electricity Board Ltd', 'Mangalore Electricity Supply Company Limited', 'Bangalore Electricity Supply Company Ltd', 'Chamundeshwari Electricity Supply Company Limited Mysore', 'Gulbarga Electricity Supply Company Limited', 'Hubli Electricity Supply Company Limited', 'Kerala State Electricity Board', 'Madhya Pradesh Paschim Kshetra Vidyut Vitran Company Limited', 'Madhya Pradesh Madhya Kshetra Vidyut Vitran Company Limited', 'Madhya Pradesh Poorv Kshetra Vidyut Vitran Company Limited', 'TATA-Power - Mumbai', 'MAHAVITARAN-Maharashtra State Electricity Distribution Co. Ltd (MSEDCL)', 'Brihanmumbai Electric Supply & Transport Undertaking for Greater Mumbai (BEST_MH)', 'Meghalaya Energy Corporation Limited', 'Supply Company of Orissa Limited (North, South, West,Central)', 'Punjab State Power Corporation Limited', 'Jaipur Vidhyut Vitran Nigam Ltd', 'Ajmer Vidhyut Vitran Nigam Ltd', 'Jodhpur Vidhyut Vitran Nigam Ltd', 'Tamil Nadu Generation and Distribution Corporation Limited - Chennai_North', 'Tamil Nadu Generation and Distribution Corporation Limited - Villupuram', 'Tamil Nadu Generation and Distribution Corporation Limited - Coimbatore', 'Tamil Nadu Generation and Distribution Corporation Limited - Erode', 'Tamil Nadu Generation and Distribution Corporation Limited - Madurai', 'Tamil Nadu Generation and Distribution Corporation Limited - Trichy', 'Tamil Nadu Generation and Distribution Corporation Limited - Tirunelvel', 'Tamil Nadu Generation and Distribution Corporation Limited - Vellore', 'Tamil Nadu Generation and Distribution Corporation Limited - Chennai_South', 'The Southern Power Distribution Company of Telangana Limited', 'Tripura State Electricity Corporation Limited', 'Kanpur Electricity Supply Company', 'UP Vidyut Vitran Nigam Limited (All Zones)', 'WEST BENGAL STATE ELECTRICITY DISTRIBUTION COMPANY LIMITED', 'Calcutta Electricity Supply Corporation Limited (CESC)', 'Jharkhand Bijli Vitran Nigam Limited (JBVNL)', 'Meghalaya Energy Corporation Limited (MeECL)', 'Manipur State Power Distribution Company Limited', 'Other'];
    }
    public function bureauReportMatchedData($consumer_application){

        $pan_percentage = 0;
        $current_address_percentage = 0;
        $permanent_address_percentage = 0;
        $co_applicant_address_percentage = 0;
        $current_address_percentageArray = [0];
        $permanent_address_percentageArray = [0];
        $co_applicant_address_percentageArray = [0];
        $panCardMatched = false;
        $numberMatched = false;
        $data = [];

        foreach($consumer_application->creditReport as $report){
            if($report) {
                $isNameExact = false;
                if ($report->applicant_type == 1) {
                    $name = $consumer_application->name;
                } else {
                    $name = $consumer_application->co_applicant_name;
                }

                $item = json_decode(str_replace('sch:', '', $report->panValidation));

                if($report->panVendor == "decentro"){
                    $kycResult = json_decode($report->panValidation);
                    if(isset($kycResult->kycResult)){
                        $item = $kycResult->kycResult;
                    }
                }
                $pan_name = "";
                if (isset($item->firstName)) {
                    $pan_name .= $item->firstName . " ";
                }
                if (isset($item->middleName)) {
                    $pan_name .= $item->middleName . " ";
                }
                if (isset($item->lastName)) {
                    $pan_name .= $item->lastName . " ";
                }

                if($report->panVendor == "decentro" && isset($item->fullName)){
                    $pan_name = $item->fullName;
                }

                if ($name == $pan_name) {
                    $isNameExact = true;
                }

                similar_text(strtolower($name), strtolower($pan_name), $pan_percentage);


                if ($report->applicant_type == 1 && $consumer_application->current_address_line_1) {
                    $addressLists = json_decode($report->AddressInfoList, 1);

                    $current_address = $consumer_application->current_address_line_1. ' ' . $consumer_application->current_address_landmark . ' ' . $consumer_application->current_address_state . ' ' . $consumer_application->current_address_city . ' ' . $consumer_application->current_address_pincode;

                    if($addressLists) {
                        foreach ($addressLists as $addressList) {
                            if (isset($addressList['Address'])) {
                                $pin = isset($addressList['Postal']) ? $addressList['Postal'] : '';
                                similar_text(strtolower($current_address), strtolower($addressList['Address'] . ' ' . $pin), $current_address_percentage);
                                $current_address_percentageArray[] = round($current_address_percentage);
                            }
                        }
                    }
                }

                if ($report->applicant_type == 1 && $consumer_application->permanent_address_line_1) {
                    $addressLists = json_decode($report->AddressInfoList, 1);

                    $permanent_address = $consumer_application->permanent_address_line_1 .' '.$consumer_application->permanent_address_landmark. ' ' . $consumer_application->permanent_address_state . ' ' . $consumer_application->permanent_address_city . ' ' . $consumer_application->permanent_address_pincode;

                    if($addressLists) {
                        foreach ($addressLists as $addressList) {
                            if (isset($addressList['Address'])) {
                                $pin = isset($addressList['Postal']) ? $addressList['Postal'] : '';
                                similar_text(strtolower($permanent_address), strtolower($addressList['Address'] . ' ' . $pin), $permanent_address_percentage);
                                $permanent_address_percentageArray[] = round($permanent_address_percentage);
                            }
                        }
                    }
                }


                if ($report->applicant_type == 2 && $consumer_application->co_applicant_address_line_1) {
                    $addressLists = json_decode($report->AddressInfoList, 1);

                    $address = $consumer_application->co_applicant_address_line_1 . ' ' . $consumer_application->co_applicant_address_landmark . ' ' . $consumer_application->co_applicant_address_state . ' ' . $consumer_application->co_applicant_address_city . ' ' . $consumer_application->co_applicant_address_pincode;

                    if($addressLists) {
                        foreach ($addressLists as $addressList) {
                            if (isset($addressList['Address'])) {
                                $pin = isset($addressList['Postal']) ? $addressList['Postal'] : '';
                                similar_text(strtolower($address), strtolower($addressList['Address'] . ' ' . $pin), $co_applicant_address_percentage);
                                $co_applicant_address_percentageArray[] = round($co_applicant_address_percentage);
                            }
                        }
                    }
                }

                $contactLists = json_decode($report->contactInfoList, 1);

                if ($report->applicant_type == 1) {
                    $mobile_number = $consumer_application->mobile_number;
                } else {
                    $mobile_number = $consumer_application->co_applicant_mobile_number;
                }

                if (strlen($mobile_number) == 10) {
                    $number91 = '91' . $mobile_number;
                    $number = $mobile_number;
                } else {
                    $number = substr($mobile_number, 0, 1) == 91 ? substr($mobile_number, 2) : $mobile_number;
                    $number91 = $mobile_number;
                }

                if ((isset($number) && is_array($contactLists) && in_array($number, $contactLists)) || (isset($number91) && is_array($contactLists) && in_array($number91, $contactLists))) {
                    $numberMatched = true;
                }

                if ($report->applicant_type == 1) {
                    $pan_card = $consumer_application->pan_card;
                } else {
                    $pan_card = $consumer_application->co_applicant_pan_card;
                }
                $panList = $report->PANIdsList ? json_decode($report->PANIdsList, 1) : [];
                if (in_array($pan_card, $panList)) {
                    $panCardMatched = true;
                }

                if ($report->applicant_type == 1) {
                    $data['name'] = ['type' => 'NPCI', 'matched' => round($pan_percentage), 'exact' => $isNameExact];
                    $data['pan_card'] = $panCardMatched ? ['type' => 'Bureau', 'matched' => 100, 'exact' => true] : ['type' => 'Bureau', 'matched' => 0, 'exact' => false];
                    $data['dob'] = $report->DateOfBirth == $consumer_application->dob ? ['type' => 'Bureau', 'matched' => 100, 'exact' => true] : ['type' => 'Bureau', 'matched' => 0, 'exact' => false];
                    $data['current_address'] = ['type' => 'Bureau', 'matched' => max($current_address_percentageArray), 'exact' => false];
                    $data['permanent_address'] = ['type' => 'Bureau', 'matched' => max($permanent_address_percentageArray), 'exact' => false];
                    $data['mobile_number'] = ['type' => 'Bureau', 'matched' => $numberMatched, 'exact' => $numberMatched ? 100 : 0];
                } else {
                    $data['co_applicant_name'] = ['type' => 'NPCI', 'matched' => round($pan_percentage), 'exact' => $isNameExact];
                    $data['co_applicant_pan_card'] = $panCardMatched ? ['type' => 'Bureau', 'matched' => 100, 'exact' => true] : ['type' => 'Bureau', 'matched' => 0, 'exact' => false];
                    $data['co_applicant_dob'] = $report->DateOfBirth == $consumer_application->co_applicant_dob ? ['type' => 'Bureau', 'matched' => 100, 'exact' => true] : ['type' => 'Bureau', 'matched' => 0, 'exact' => false];
                    $data['co_applicant_address'] = ['type' => 'Bureau', 'matched' => max($co_applicant_address_percentageArray), 'exact' => false];
                    $data['co_applicant_mobile_number'] = ['type' => 'Bureau', 'matched' => $numberMatched, 'exact' => $numberMatched ? 100 : 0];
                }
            }
        }

        return $data;
    }

    public function createConsumerLead(){
        $lead = true;
        $data = $this->create($lead);
        $data['page_type'] = 'lead';
        return view('admin.consumer-application.edit_v1', $data);
    }

//    public static function getStateFromGooglegetStates(Request $request){
//        $state = PWAApplicationForm::getStateFromGoogle($request->get('pincode'));
//        return \response()->json(['status' => 'OK','state' => $state]);
//    }

    public function reviewDetails(Request $request)
    {
        if ($errorCode = (new ApiController())->checkEligibility($request, true)) {
            $data['error']['eligibility'] = $errorCode;
            return response()->json($data, 200);
        }
        $data['error']['eligibility'] = $errorCode;

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

    public function stopMultipleLogin($r){
        $recentLogin = ConsumerApplication::where('email',$r->get('email'))->where('mobile_number',$r->get('mobile_number'))->where('pan_card',$r->get('pan_card'))->where('created_at','<=',Carbon::now()->toDateTimeString())->where('created_at','>=',Carbon::now()->subMinute()->toDateTimeString())->whereNull('is_deleted')->first(['id']);

        if(isset($recentLogin)){
            // already exist then stop data insertion second time
            return false;
        }else{
            // not exist then insert data
            return true;
        }
    }

    public function store(Request $request, $leads = false)
    {
        $validationRules = [
            "first_name" => "nullable|string",
            "middle_name" => "nullable|string",
            "last_name" => "nullable|string",
            "gender" => "nullable|string",
            "email" => "required|string|regex:/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[_a-z0-9-]+)*(\.[a-z]{2,})$/i",
            "mobile_number" => "required|numeric|digits:10",
            "merchant_id" => "required|numeric",
            "purpose" => "required"
        ];

        if (!$leads) {
            // Add dob validation only if $leads is false
            $validationRules['dob'] = ['required', function ($attribute, $value, $fail) {
                $age = Carbon::parse($value)->diff(Carbon::now())->y;
                if ($age >= 65) {
                    $fail('Age over 64. Applicants who are ' . $age . ' years are ineligible for loans');
                }
            }];
        }

        $validation = Validator::make($request->all(), $validationRules, [
            "string" => ":attribute is not string",
            "digits" => ":attribute is not in proper length",
            "numeric" => ":attribute is not number",
            "required" => ":attribute is required",
        ]);
        if($validation->messages()->all()){
            $data = [
                "status" => "FAIL",
                "message" => $validation->messages()->all(),
                "error" => [
                    "code" => "400",
                    "message" => "Bad Request"
                ]
            ];
            \Session::flash('error', json_encode($data['message']));
            return redirect()->back();
        }
        $actionType = $request->input('action_type'); // Get the action type

        $multiplelogin = $this->stopMultipleLogin($request);

        if($multiplelogin){
            if ($errorCode = (new ApiController())->checkEligibility($request)) {
    //            \Session::flash('error', 'Repeat Customer! <a href="/admin/consumer-applications/edit/'.$errorCode.'">');
                \Session::flash('error', 'Repeat Customer!');
            }

            $paddress1 = preg_replace('/[^\p{L}\p{N}\s]/u', '', $request->loan_amount);

            $paddress1 = str_replace("'","", str_replace('"','', $request->per_address_1));
            $paddress2 = str_replace("'","", str_replace('"','', $request->per_address_2));
            $paddress3 = str_replace("'","", str_replace('"','', $request->per_address_3));
            $request->merge(['permanent_address_line_1' => $paddress1.$paddress2.$paddress3]);
            // $request->merge(['permanent_address_line_1' => str_replace("'","", str_replace('"','', $request->permanent_address_line_1))]);
            $request->merge(['permanent_address_city' => str_replace("'","", str_replace('"','', $request->permanent_address_city))]);
            $request->merge(['permanent_address_landmark' => str_replace("'","", str_replace('"','', $request->permanent_address_landmark))]);
            $curddress1 = str_replace("'","", str_replace('"','', $request->cur_address_1));
            $curddress2 = str_replace("'","", str_replace('"','', $request->cur_address_2));
            $curddress3 = str_replace("'","", str_replace('"','', $request->cur_address_3));
            $request->merge(['current_address_line_1' => $curddress1.$curddress2.$curddress3]);
            // $request->merge(['current_address_line_1' => str_replace("'","", str_replace('"','', $request->current_address_line_1))]);
            $request->merge(['current_address_city' => str_replace("'","", str_replace('"','', $request->current_address_city))]);
            $request->merge(['current_address_landmark' => str_replace("'","", str_replace('"','', $request->current_address_landmark))]);

            /*insert into ConsumerApplication*/
            $consumer_application = new \App\ConsumerApplication();
            $consumer_application->fill($request->input());
            
            if (empty($consumer_application->lender_id)) {
                $consumer_application->lender_id = 20;
            }
            
            if($request->get('loan_amount')) {
                $consumer_application->loan_amount = preg_replace('/[^\p{L}\p{N}\s]/u', '', $request->get('loan_amount'));
            }
            if($request->get('approved_amount')) {
                $consumer_application->approved_amount = preg_replace('/[^\p{L}\p{N}\s]/u', '', $request->get('approved_amount'));
            }
            $consumer_application->name = $this->getFullName($request);
            if (Auth::check() && Auth::user()->user_type == UserTypes::$merchant_v2) {
                $consumer_application->updated_by = 'merchant admin panel';
            } else {
                $consumer_application->updated_by = 'admin';
            }
            $consumer_application->co_applicant_dob = $request->co_applicant_dob && $request->co_applicant_dob != '1970-01-01' ? date("Y-m-d", strtotime($request->co_applicant_dob)) : null;
            $consumer_application->created_by = Auth::user()->id;
            if($leads || $request->has('project_lead')) {
                $consumer_application->state = 'incomplete form';
                $consumer_application->dob = $request->dob && $request->dob != '1970-01-01' ? date("Y-m-d", strtotime($request->dob)) : null;
            }else{
                $consumer_application->dob = $request->dob && $request->dob != '1970-01-01' ? date("Y-m-d", strtotime($request->dob)) : null;
                $consumer_application->state = 'form completed';
            }

            if ($request->has('company_name')) {
                if (is_null($request->get('company_name')) && !empty($request->get('company_name_search'))) {
                    $CompanyID = Company::insertGetId([
                        'category' => 'CAT D',
                        'company' => $request->get('company_name_search'),
                    ]);
                    $consumer_application->company_name = $CompanyID;
                }
            }

            if ($request->has('co_applicant_company_name_search')) {
                if (is_null($request->get('co_applicant_company_name')) && !empty($request->get('co_applicant_company_name_search'))) {
                    $CompanyID = Company::insertGetId([
                        'category' => 'CAT D',
                        'company' => $request->get('co_applicant_company_name_search'),
                    ]);
                    $consumer_application->co_applicant_company_name = $CompanyID;
                }
            }

            if ($request->has('offer_id') && $request->get('offer_id')) {
                $merchantOffer = MerchantOffers::where('id', $request->get('offer_id'))->first(['tenure']);
                $consumer_application->tenure = isset($merchantOffer->tenure) ? $merchantOffer->tenure : 0;
            }

            /*if(!$leads || $request->has('project_lead')){*/
                $customer = $consumer_application->saveCustomer();
                $consumer_application->applicant_id = $customer->applicant_id;
                $consumer_application->co_applicant_id = $customer->co_applicant_id;
            /*}*/

            $application_user_id = $this->userCreation($consumer_application, true, $request);
            $consumer_application->user_id = $application_user_id;

            $consumer_application->save();

            (new ContentLogger())->logger($consumer_application, 'consumer_application', true);


            if (!empty($request->get('cpv_longitude')) && !empty($request->get('cpv_latitude'))) {
                $this->saveUserGeolocation($consumer_application, ['applicant_type' => 1, 'id_type' => 'application_id', 'service' => 'cpv', 'longitude' => $request->get('cpv_longitude'), 'latitude' => $request->get('cpv_latitude')]);
            }


            UserEmails::validates(['emails' => [$request->get('email'), $request->get('co_applicant_email'), $request->get('work_email')], 'type' => 'application_id', 'id' => $consumer_application->id]);

            if ($request->get('name')) {
                $merchant = '';
                if ($request->get('merchant_id')) {
                    $merchant = Merchant::find($request->get('merchant_id'));
                }
                $info = (isset($merchant->merchant_name) && !empty($merchant->merchant_name)) ? $merchant->merchant_name : $request->get('mobile_number');
                $request->attributes->add(['title' => $request->get('name') . ' (' . $info . ')']);
                (new Trello($request))->insertInTrello();
            }

            if ($request->has('documents') && count(array_diff($request->get('documents'), [null]))) {
                $this->uploadConsumerDocuments($request, $consumer_application->id);
            }
            if ($request->hasFile('img_address_details')) {
                $file_type = $request->get('img_address_details_type');
                if($file_type == 'aadhar_card' || $file_type == 'Aadhaar Front Top' || $file_type == 'Aadhaar Front Bottom' || $file_type == 'Aadhaar Back') {
                    $file_type = 'aadhar_card';
                }
                $this->uploadSingleFile($consumer_application->id, $file_type, $request->file('img_address_details'), $request);
            }
            if ($request->hasFile('img_coApp_address_details')) {
                $file_type = $request->get('img_coApp_address_details_type');
                if($file_type == 'aadhar_card' || $file_type == 'Aadhaar Front Top' || $file_type == 'Aadhaar Front Bottom' || $file_type == 'Aadhaar Back') {
                    $file_type = 'co-applicant_aadhar_card';
                }
                $this->uploadSingleFile($consumer_application->id, $file_type, $request->file('img_coApp_address_details'), $request);
            }
            if ($request->hasFile('img_pan_details')) {
                $this->uploadSingleFile($consumer_application->id, 'pan_card', $request->file('img_pan_details'), $request);
            }
            if ($request->hasFile('img_coApp_pan_details')) {
                $this->uploadSingleFile($consumer_application->id, 'co-applicant_pan_card', $request->file('img_coApp_pan_details'), $request);
            }

            $applicationElementObject = ConsumerApplicationElement::where('application_id', $consumer_application->id)->first();
            $applicationAdditionObject = ConsumerApplicationAdditional::where('application_id', $consumer_application->id)->first();

            if (!isset($applicationElementObject->id)) {
                $applicationElementObject = new ConsumerApplicationElement();
                $applicationElementObject->application_id = $consumer_application->id;
            }
            if (!isset($applicationAdditionObject->id)) {
                $applicationAdditionObject = new ConsumerApplicationAdditional();
                $applicationAdditionObject->application_id = $consumer_application->id;
            }

            $product_name = $request->get('product_name') && is_array($request->get('product_name')) ? implode(',',$request->get('product_name')) : $request->get('product_name');
            if(!$product_name){
                $product_name = $request->get('product_name_str') ? $request->get('product_name_str') : '';
            }

            if(strpos($request->path(),'bnpl-application')){
                $applicationElementObject->is_bnpl = 1;
            }

            $applicationElementObject->fill($request->all());
            $applicationElementObject->product_name = $product_name;
            $applicationElementObject->co_applicant_profession_type = $request->get('co_applicant_profession');
            $applicationElementObject->merchant_representative_name = $request->get('merchant_representative_name');
            $applicationElementObject->merchant_representative_mobile = $request->get('merchant_representative_mobile');
            $applicationElementObject->merchant_representative_email = $request->get('merchant_representative_email');
            $applicationElementObject->profession_type = $request->get('profession');
            $applicationElementObject->co_applicant_for_signing = $request->has('co_applicant_for_signing') ? 1 : 2;
            $applicationElementObject->co_applicant_for_income = $request->has('co_applicant_for_income') ? 1 : 2;
            $applicationElementObject->duration = $request->get('duration_month') . '|' . $request->get('duration_year');
            $applicationElementObject->collection_advisor = $request->has('collection_advisor') && $request->get('collection_advisor') > 0 ? $request->get('collection_advisor') : 0;
            $applicationElementObject->installation_address_city = $request->has('installation_address_city') ? $request->get('installation_address_city') : "";
            $applicationElementObject->installation_address_state = $request->has('installation_address_state') ? $request->get('installation_address_state') : "";
            $applicationElementObject->installation_address_pincode = $request->has('installation_address_pincode') ? $request->get('installation_address_pincode') : "";
            $applicationElementObject->installation_address_status = $request->has('installation_address_status') ? $request->get('installation_address_status') : "";
            $applicationElementObject->installation_address_landmark = $request->has('installation_address_landmark') ? $request->get('installation_address_landmark') : "";
            $applicationElementObject->installation_address_line_1 = ($request->has('installation_address_1') ? $request->get('installation_address_1') : "") . '' .($request->has('installation_address_2') ? $request->get('installation_address_2') : "") . '' .($request->has('installation_address_3') ? $request->get('installation_address_3') : "");

            if ($request->has('offer_id') && $request->get('offer_id') != '') {
                $applicationAdditionObject->initial_applied_tenure = $request->get('offer_id');
            }
            $applicationAdditionObject->is_comm_no_linked_to_aadhar = $request->has('is_comm_no_linked_to_aadhar') ? $request->get('is_comm_no_linked_to_aadhar') : null;
            $applicationAdditionObject->aadhar_linked_mobile = $request->has('aadhar_linked_mobile') ? $request->get('aadhar_linked_mobile') : null;
            $applicationAdditionObject->coapp_is_comm_no_linked_to_aadhar = $request->has('coapp_is_comm_no_linked_to_aadhar') ? $request->get('coapp_is_comm_no_linked_to_aadhar') : null;
            $applicationAdditionObject->coapplicant_aadhar_linked_mobile = $request->has('coapplicant_aadhar_linked_mobile') ? $request->get('coapplicant_aadhar_linked_mobile') : null;
            $applicationAdditionObject->co_applicant_required_for_mandate = $request->has('co_applicant_required_for_income_and_mandate') ? 1 : 2;

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

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

                $applicationElementObject->inverter_model_description =$request->has('model_description') ? $request->get('model_description') : null;
                $applicationElementObject->inverter_monthly_power_bill =$request->get('monthly_power_bill');
                $applicationElementObject->type_of_customer =$request->get('type_of_customer');
                $applicationElementObject->solar_power_type =$request->get('type_of_solar_power');
                $applicationElementObject->inverter_KW_installation =$request->get('KW_installation');
                $applicationElementObject->inverter_gross_project_amount =$request->get('gross_project_amount');
                $applicationElementObject->inverter_subsidy_amount =$request->get('subsidy_amount');
                $applicationElementObject->inverter_power_savings = $request->get('power_savings');
                // $applicationElementObject->discount_by_cf = $request->get('solar_discount_by_cf') ?? 0;
                $applicationElementObject->login_id_of_installer = $request->get('login_id_of_installer');
                $applicationElementObject->password = $request->get('installer_password');
                // $applicationElementObject->website_link = $request->get('website_link');
                $applicationElementObject->discom_service_provider = $request->get('service_provider');
                if(strtolower($request->get('service_provider')) == "other"){
                    $applicationElementObject->other_discom_service_provider = $request->get('other_service_provider');
                }
            }

            if ($request->has('electricity_name_change')) {
                $applicationElementObject->electricity_name_change = $request->get('electricity_name_change');
            }

            if($leads || $request->has('project_lead')){
                $status = 'incomplete form';
                $applicationElementObject->soft_lead = 1;
            }else{
                $status =  'form completed';
            }
            $applicationElementObject->save();

            if ($request->has('offer_id') && $request->get('offer_id')) {
                $merchantOffer = \App\MerchantOffers::find($request->get('offer_id'));
                if ($merchantOffer) {
                    $consumer_application->application_element = $applicationElementObject;
                    $ltv = (new GradeController(new Request()))->calculateLTV($consumer_application, $merchantOffer);
                    $applicationAdditionObject->loan_to_value_limit = [
                        'ltv_gross_project_amount' => $ltv['ltv_gross_project_amount'],
                        'ltv_net_loan_amount' => $ltv['ltv_net_loan_amount'],
                    ];

                    $comment = "Initial LTV Value Set.<br>LTV (Gross Project Amount): " . number_format($ltv['ltv_gross_project_amount'], 2) . "%<br>LTV (Net Loan Amount): " . number_format($ltv['ltv_net_loan_amount'], 2) . "%<br>Loan Amount: " . $ltv['loan_amount'] . " <br>Gross Project Amount: " . $ltv['inverter_gross_project_amount'] . " <br>Net Loan Amount: " . $ltv['net_loan_amount'];
                    $this->addComment($consumer_application->id, $comment);

                    ContentLogger::insert([
                        'application_id' => $consumer_application->id,
                        'data' => json_encode([
                            'ltv_gross_project_amount' => ['old' => '', 'new' => round((float)$ltv['ltv_gross_project_amount'], 2)],
                            'ltv_net_loan_amount' => ['old' => '', 'new' => round((float)$ltv['ltv_net_loan_amount'], 2)],
                        ]),
                        'status' => $consumer_application->state ?? '',
                        'created_at' => Carbon::now()->toDateTimeString(),
                        'user_id' => Auth::user() ? Auth::user()->id : 107,
                        'model' => 'consumer_application'
                    ]);
                }
            }
            $applicationAdditionObject->save();

            if($request->has('reference_id') && !empty($request->get('reference_id'))){
                $this->initiateCKYC($request , $consumer_application->id);
            }

            $this->updateProformaAttributes($consumer_application->id, $request);

            StatusLogs::insert([
                'application_id' => $consumer_application->id,
                'user_id' => Auth::user()->id,
                'status' => $status,
                'created_at' => Carbon::now()->toDateTimeString()
            ]);
            $this->sendMessageOnWhatsApp($consumer_application->id, $request->has('project_lead') ? 'project_lead' : 'admin');
            $this->sendMessageBeforeBureauPull($consumer_application->id);
            if ($consumer_application->state === 'form completed') {
                // application status changed to form completed
                try {
                    event(new EventPostFormCompleted($consumer_application->id));
                }catch (\Exception $e){

                }
            }
            if($leads){
                $this->sendslackmessage($consumer_application->id, $status, '', '- Lead Application');
                \Session::flash('success', 'Lead Application successfully Added');
                return true;
            }elseif($request->has('project_lead')){
                return $consumer_application->id;
            }else{
                $this->sendslackmessage($consumer_application->id, $status);
                \Session::flash('success', 'Aplication successfully Added');
                if(strpos($request->path(),'bnpl-application')){
                    return redirect()->to('admin/bnpl-applications');
                }
                if ($actionType === 'save') {
                    return redirect()->to('admin/consumer-applications/edit/'.(string)$consumer_application->id);
                }else{
                    return redirect()->to('admin/consumer-applications');
                }
            }
        }else{
            if(strpos($request->path(),'bnpl-application')){
                return redirect()->to('admin/bnpl-applications');
            }
            return redirect()->to('admin/consumer-applications');
        }
    }

    public function leadStore(Request $request){
        $this->store($request, true);
        return redirect()->to('admin/consumer-applications');
    }

    public function saveSolarCase(Request $request)
    {

    // Find the existing record by application_id
    $appID = $request->has('application_id') ? $request->get('application_id') : "";
    if($appID == ""){
        return response()->json(['success' => false]);
    }
    $applicationElementObject = ConsumerApplicationElement::where('application_id', $appID)->first();
    if (!isset($applicationElementObject->id)) {
        $applicationElementObject = new ConsumerApplicationElement();
        $applicationElementObject->application_id = $appID;
    }

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

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

            $applicationElementObject->inverter_monthly_power_bill = $request->has('monthly_power_bill') ? $request->get('monthly_power_bill') : null;
            $applicationElementObject->type_of_customer = $request->has('type_of_customer') ? $request->get('type_of_customer') : null;
            $applicationElementObject->solar_power_type = $request->has('type_of_solar_power') ? $request->get('type_of_solar_power') : null;
            $applicationElementObject->inverter_KW_installation = $request->has('KW_installation') ? $request->get('KW_installation') : null;
            $applicationElementObject->inverter_gross_project_amount = $request->has('gross_project_amount') ? $request->get('gross_project_amount') : null;
            $applicationElementObject->inverter_power_savings = $request->has('power_savings') ? $request->get('power_savings') : null;
            $applicationElementObject->discom_service_provider = $request->has('service_provider') ? $request->get('service_provider') : null;
            $applicationElementObject->type_of_customer_sub_category = $request->has('type_of_customer_sub_category') ? $request->get('type_of_customer_sub_category') : null;
            if(strtolower($request->get('service_provider')) == "other"){
                $applicationElementObject->other_discom_service_provider = $request->has('other_service_provider') ? $request->get('other_service_provider') : null;
            }
            $applicationElementObject->save();
        }

        if ($request->has('electricity_name_change')) {
            $applicationElementObject->electricity_name_change = $request->get('electricity_name_change');
            $applicationElementObject->save();
        }

        return response()->json(['success' => true]);
    }

    public function uploadSingleFile($id, $type, $file, $request)
    {
        $file_path = '/' . $id . '/' . $type . '.' . $file->getClientOriginalExtension();
        $s3 = Storage::disk('s3');
        $s3->put($file_path, $file);
        $data['file_type'] = $type;
        $data['id'] = $id;
        $this->getUploadedFileNameMultiple($s3, $file_path, $data);
//        $s3_path = $this->getUploadedFileName($s3, $file_path);
//        $this->uploadConsumerFiles($id, $type, $s3_path, $request);
    }

    public function initiateCKYC(Request $request, $id){
        DecentroCkyc::where('reference_id',$request->get('reference_id'))->update(['application_id'=>$id]);
        $s3 = Storage::disk('s3');
        $fileName = $request->get('reference_id') . '/' . $request->get('reference_id') . "_response_decentro_ckyc_download.json";
        if ($s3->exists($fileName)) {
            $getData = $s3->get($fileName);
            $count = DecentroCkyc::where('reference_id', $request->get('reference_id'))->first(['updatedDate']);
            $date1 = Carbon::parse($count->updatedDate);
            $today = Carbon::now()->endOfDay()->toDateTimeString();
            $date2 = Carbon::parse($today);
            $diffDays = $date1->diffInDays($date2);
            if ($diffDays <= 365) {
                $consumerDocument = new ConsumerDocument(new Request(['reference_id'=>$request->get('reference_id')]));
                $res = json_decode($getData);
                foreach ($res->data->kycResult->personalIdentifiableData->imageDetails->image as $val) {
                    if (isset($val->imageCode) && $val->imageCode == "Photograph") {
                        $consumerDocument->uploadToS3('customer_photo', $id, base64_decode($val->imageData, '.' . strtolower($val->imageType)));
                    }
                    if (isset($val->imageCode) && $val->imageCode == "PAN") {
                        $consumerDocument->uploadToS3('pan_card', $id, base64_decode($val->imageData, '.' . strtolower($val->imageType)));
                    }
                    if (isset($val->imageCode) && $val->imageCode == "Signature") {
                        $consumerDocument->uploadToS3('signature_' . $id . '_1', $id, base64_decode($val->imageData, '.' . strtolower($val->imageType)));
                    }
                    if (isset($val->imageCode) && $val->imageCode == "Voters Identity Card") {
                        $consumerDocument->uploadToS3('votar_id_front', $id, base64_decode($val->imageData, '.' . strtolower($val->imageType)));
                    }
                    if (isset($val->imageCode) && $val->imageCode == "Proof of Possession of Aadhaar") {
                        $consumerDocument->uploadToS3('aadhar_card', $id, base64_decode($val->imageData, '.' . strtolower($val->imageType)));
                    }
                }
            }
        }
    }

    public function updateMerchantRepresentativeDetails($id){
        try {
            $application_element = ConsumerApplicationElement::where('application_id', $id)->first(['merchant_representative_name', 'merchant_representative_mobile', 'merchant_representative_email']);
            if ($application_element && !$application_element->merchant_representative_name && !$application_element->merchant_representative_mobile && !$application_element->merchant_representative_email) {
                $application = ConsumerApplication::where('id', $id)->first(['src_representative_name']);
                if (isset($application->src_representative_name) && $application->src_representative_name) {
                    $src_representative_name_details = User::where('id',$application->src_representative_name)->whereIn('user_type',[2,3,4])->first(['id', 'name', 'mobile_number', 'email']);
                    if (isset($src_representative_name_details->id)) {
                        ConsumerApplicationElement::where('application_id', $id)->update(['merchant_representative_name' => $src_representative_name_details->name, 'merchant_representative_mobile' => $src_representative_name_details->mobile_number, 'merchant_representative_email' => $src_representative_name_details->email]);
                    }
                }
            }
        }catch (\Exception $e){

        }
    }

    public function checkCoApplicantConsent(Request $request)
    {
        $applicationId = $request->input('application_id');

        // Retrieve the application
        $application =  ConsumerApplication::where('id', $applicationId)->first(['co_applicant_name']);

        if (!$application) {
            return response()->json([
                'success' => false,
                'message' => 'Application not found'
            ], 404);
        }
        $hasConsent = true;
        if(isset($application->co_applicant_name)){
            $coAppConsent = ConsumerApplicationFiles::where([
                ['consumer_application_id', $applicationId],
                ['file_type', 'co_app_consent_logs'],
                ['applicant_type', 2]
            ])->exists();

            if (!$coAppConsent) {
                $hasConsent = false;
            }}
        // Check if co-applicant consent is present

        return response()->json([
            'success' => true,
            'has_consent' => $hasConsent
        ]);
        
    }

    public function edit($id, $is_bnpl = false){
        if(!is_numeric($id)){
            \Session::flash('error', 'Application does not exist');
            return redirect()->to('/admin/consumer-applications');
        }

        if(!LenderServices::accessible($id, $this->statusreversearray)){
            Session::flash('error', 'You don\'t have permission to view the page');
            return redirect()->back();
        }
        $app = ConsumerApplicationElement::where('application_id', $id)->first(['application_id','is_bnpl', 'unique_id_number']);
        if($is_bnpl && !$app->is_bnpl){
            Session::flash('error', 'This is not a BNPL application');
            return redirect()->back();
        }elseif(!$is_bnpl && $app && $app->is_bnpl){
            Session::flash('error', 'This is not a EMI application');
            return redirect()->back();
        }

        if(($is_bnpl && !\Illuminate\Support\Facades\Session::has('BNPL_Applications_Update|2-8-2')) || (Auth::user()->user_type == _env('AVANSE_USER_TYPE', 27) && ((Auth::user()->lender_id == 2 && $app->unique_id_number != 'avanse_da') && !in_array($app->application_id, [173589,
                    179991,
                    182604,
                    183167,
                    187304,
                    188806,
                    192154,
                    196290,
                    196658,
                    197474,
                    197860,
                    199564,
                    199647,
                    200285,
                    200519,
                    201022,
                    201479,
                    202157,
                    203000,
                    203158,
                    203194,
                    203339,
                    204020,
                    204317,
                    206302,
                    206358,
                    206663,
                    206829,
                    207288,
                    207357,
                    207582,
                    207859,
                    208687,
                    209695,
                    210427,
                    210935,
                    211130,
                    211246,
                    211271,
                    211774,
                    211925,
                    212131,
                    212498,
                    212528,
                    212631,
                    212675,
                    213195,
                    213689,
                    214587,
                    215088,
                    215404,
                    215689,
                    215743,
                    216027,
                    216408,
                    217019,
                    217189,
                    217708,
                    217959,
                    218467,
                    218487,
                    218977,
                    220578,
                    220712,
                    221223,
                    221259,
                    221321,
                    221358,
                    222372,
                    222516,
                    222734,
                    222771,
                    223122,
                    223332,
                    223461,
                    224274,
                    224519,
                    224653,
                    224684,
                    224786,
                    225011,
                    225132,
                    225197,
                    225240,
                    225483,
                    225530,
                    225689,
                    225766,
                    225880,
                    226313,
                    226431,
                    226690,
                    226794,
                    226862,
                    227013,
                    227030,
                    227043,
                    227111,
                    227417,
                    227704,
                    227895,
                    228001,
                    228092,
                    228193,
                    228203,
                    228234,
                    228517,
                    228586,
                    228769,
                    228780,
                    228845,
                    229016,
                    229068,
                    229073,
                    229130,
                    229343,
                    229501,
                    229542,
                    229578,
                    229750,
                    229761,
                    229786,
                    229791,
                    229840,
                    229933,
                    230003,
                    230118,
                    230277,
                    230284,
                    230351,
                    230362,
                    230364,
                    230401,
                    230754,
                    230840,
                    230892,
                    230921,
                    231107,
                    231194,
                    231247,
                    231287,
                    231297,
                    231378,
                    231484,
                    231550,
                    231618,
                    231735,
                    231860,
                    231977,
                    231990,
                    232075,
                    232091,
                    232100,
                    232133,
                    232312,
                    232388,
                    232538,
                    232610,
                    232769,
                    232867,
                    232973,
                    232989,
                    233078,
                    233091,
                    233186,
                    233249,
                    233302,
                    233308,
                    233310,
                    233421,
                    233471,
                    233580,
                    233737,
                    233746,
                    234054,
                    234063,
                    234248,
                    234270,
                    234293,
                    234339,
                    234357,
                    234399,
                    234404,
                    234405,
                    234415,
                    234472,
                    234532,
                    234569,
                    234572,
                    234735,
                    234739,
                    234867,
                    234910,
                    235038,
                    235079,
                    235172,
                    235253,
                    235301,
                    235436,
                    235450,
                    235494,
                    235603,
                    235604,
                    235702,
                    235806,
                    235909,
                    236040,
                    236099,
                    236124,
                    236141,
                    236207,
                    236284,
                    236295,
                    236363,
                    236592,
                    236614,
                    236617,
                    236659,
                    236832,
                    236846,
                    236928,
                    236969,
                    236971,
                    236981,
                    237143,
                    237146,
                    237200,
                    237284,
                    237291,
                    237293,
                    237344,
                    237350,
                    237353,
                    237468,
                    237480,
                    237606,
                    237753,
                    237886,
                    237919,
                    237997,
                    238057,
                    238063,
                    238090,
                    238092,
                    238181,
                    238200,
                    238229,
                    238238,
                    238251,
                    238283,
                    238323,
                    238371,
                    238386,
                    238389,
                    238457,
                    238617,
                    238696,
                    238699,
                    238845,
                    238953,
                    238996,
                    239038,
                    239117,
                    239176,
                    239196,
                    239214,
                    239244,
                    239281,
                    239423,
                    239462,
                    239568,
                    239622,
                    239690,
                    239834,
                    239851,
                    239899,
                    239931,
                    239948,
                    240007,
                    240015,
                    240087,
                    240134,
                    240160,
                    240199,
                    240203,
                    240232,
                    240312,
                    240343,
                    240385,
                    240490,
                    240506,
                    240529,
                    240555,
                    240699,
                    240799,
                    240800,
                    240913,
                    241000,
                    241018,
                    241022,
                    241047,
                    241074,
                    241110,
                    241132,
                    241134,
                    241144,
                    241149,
                    241157,
                    241190,
                    241214,
                    241298,
                    241310,
                    241412,
                    241523,
                    241551,
                    241578,
                    241579,
                    241682,
                    241762,
                    241793,
                    241967,
                    241984,
                    242042,
                    242103,
                    242138,
                    242162,
                    242185,
                    242189,
                    242211,
                    242223,
                    242302,
                    242372,
                    242427,
                    242515,
                    242556,
                    242575,
                    242758,
                    242781,
                    242795,
                    242848,
                    242859,
                    242896,
                    242915,
                    242928,
                    242944,
                    243044,
                    243078,
                    243161,
                    243180,
                    243190,
                    243222,
                    243223,
                    243238,
                    243310,
                    243337,
                    243377,
                    243416,
                    243437,
                    243519,
                    243545,
                    243605,
                    243659,
                    243782,
                    243800,
                    243812,
                    243826,
                    243828,
                    243832,
                    243864,
                    243926,
                    243953,
                    243971,
                    244047,
                    244091,
                    244138,
                    244284,
                    244491,
                    244504,
                    244509,
                    244545,
                    244552,
                    244684,
                    244687,
                    244704,
                    244753,
                    244809,
                    244827,
                    244898,
                    244906,
                    244940,
                    244967,
                    244980,
                    244983,
                    245032,
                    245090,
                    245104,
                    245136,
                    245193,
                    245196,
                    245208,
                    245272,
                    245284,
                    245302,
                    245357,
                    245358,
                    245360,
                    245564,
                    245593,
                    245666,
                    245673,
                    245680,
                    245777,
                    245798,
                    245859,
                    245927,
                    245958,
                    245975,
                    245983,
                    245989,
                    246003,
                    246008,
                    246021,
                    246031,
                    246032,
                    246053,
                    246066,
                    246088,
                    246117,
                    246129,
                    246148,
                    246187,
                    246263,
                    246301,
                    246340,
                    246360,
                    246380,
                    246395,
                    246432,
                    246502,
                    246610,
                    246624,
                    246708,
                    246732,
                    246833,
                    246870,
                    246912,
                    246939,
                    247025,
                    247055,
                    247166,
                    247189,
                    247202,
                    247214,
                    247215,
                    247255,
                    247274,
                    247345,
                    247459,
                    247501,
                    247523,
                    247547,
                    247580,
                    247599,
                    247604,
                    247635,
                    247651,
                    247685,
                    247699,
                    247711,
                    247741,
                    247752,
                    247759,
                    247776,
                    247780,
                    247784,
                    247806,
                    247832,
                    247881,
                    247911,
                    247930,
                    247957,
                    247965,
                    248001,
                    248059,
                    248101,
                    248115,
                    248173,
                    248183,
                    248202,
                    248288,
                    248427,
                    248439,
                    248538,
                    248576,
                    248584,
                    248599,
                    248603,
                    248621,
                    248717,
                    248811,
                    248843,
                    248872,
                    248874,
                    248915,
                    248960,
                    249003,
                    249015,
                    249039,
                    249080,
                    249090,
                    249095,
                    249115,
                    249147,
                    249150,
                    249211,
                    249261,
                    249268,
                    249303,
                    249319,
                    249406,
                    249446,
                    249520,
                    249534,
                    249601,
                    249609,
                    249614,
                    249623,
                    249633,
                    249648,
                    249654,
                    249659,
                    249675,
                    249731,
                    249740,
                    249766,
                    249783,
                    249786,
                    249789,
                    249911,
                    249912,
                    249928,
                    249965,
                    250007,
                    250087,
                    250089,
                    250093,
                    250119,
                    250144,
                    250181,
                    250312,
                    250353,
                    250372,
                    250440,
                    250477,
                    250503,
                    250511,
                    250516,
                    250565,
                    250606,
                    250633,
                    250638,
                    250661,
                    250683,
                    250718,
                    250725,
                    250750,
                    250767,
                    250777,
                    250861,
                    250864,
                    250873,
                    250881,
                    250896,
                    250909,
                    250916,
                    250921,
                    250928,
                    250940,
                    250954,
                    250987,
                    250989,
                    251028,
                    251125,
                    251128,
                    251140,
                    251159,
                    251171,
                    251172,
                    251193,
                    251202,
                    251289,
                    251300,
                    251310,
                    251349,
                    251371,
                    251406,
                    251449,
                    251472,
                    251474,
                    251495,
                    251500,
                    251555,
                    251559,
                    251578,
                    251579,
                    251630,
                    251631,
                    251675,
                    251685,
                    251693,
                    251759,
                    251800,
                    251887,
                    251893,
                    251909,
                    251924,
                    251947,
                    251955,
                    251996,
                    252007,
                    252012,
                    252014,
                    252032,
                    252106,
                    252138,
                    252145,
                    252170,
                    252268,
                    252293,
                    252294,
                    252331,
                    252348,
                    252455,
                    252477,
                    252498,
                    252508,
                    252514,
                    252560,
                    252564,
                    252589,
                    252599,
                    252610,
                    252644,
                    252652,
                    252656,
                    252670,
                    252699,
                    252783,
                    252804,
                    252816,
                    252835,
                    252897,
                    252901,
                    252925,
                    252950,
                    252982,
                    253029,
                    253035,
                    253040,
                    253078,
                    253086,
                    253111,
                    253134,
                    253159,
                    253165,
                    253169,
                    253180,
                    253207,
                    253277,
                    253285,
                    253309,
                    253348,
                    253403,
                    253430,
                    253469,
                    253476,
                    253532,
                    253547,
                    253552,
                    253567,
                    253598,
                    253634,
                    253657,
                    253809,
                    253838,
                    253870,
                    253871,
                    253883,
                    253885,
                    253907,
                    253927,
                    253934,
                    253936,
                    253941,
                    253944,
                    254006,
                    254015,
                    254031,
                    254032,
                    254055,
                    254075,
                    254143,
                    254159,
                    254167,
                    254186,
                    254218,
                    254240,
                    254255,
                    254293,
                    254298,
                    254302,
                    254351,
                    254360,
                    254410,
                    254413,
                    254417,
                    254443,
                    254498,
                    254528,
                    254554,
                    254564,
                    254566,
                    254583,
                    254599,
                    254652,
                    254707,
                    254746,
                    254759,
                    254761,
                    254813,
                    254832,
                    254840,
                    254843,
                    254849,
                    254876,
                    254883,
                    254892,
                    255036,
                    255102,
                    255117,
                    255129,
                    255154,
                    255173,
                    255188,
                    255301,
                    255306,
                    255392,
                    255419,
                    255437,
                    255478,
                    255515,
                    255534,
                    255587,
                    255590,
                    255609,
                    255691,
                    255736,
                    255760,
                    255770,
                    255806,
                    255819,
                    255834,
                    255844,
                    255864,
                    255930,
                    255950,
                    255998,
                    256020,
                    256054,
                    256065,
                    256067,
                    256085,
                    256100,
                    256105,
                    256116,
                    256117,
                    256122,
                    256126,
                    256136,
                    256151,
                    256266,
                    256278,
                    256319,
                    256342,
                    256351,
                    256372,
                    256393,
                    256405,
                    256445,
                    256452,
                    256456,
                    256562,
                    256660,
                    256688,
                    256742,
                    256804,
                    256821,
                    256890,
                    256939,
                    256954,
                    256956,
                    256979,
                    257001,
                    257031,
                    257047,
                    257059,
                    257079,
                    257087,
                    257156,
                    257163,
                    257186,
                    257188,
                    257278,
                    257342,
                    257358,
                    257400,
                    257431,
                    257437,
                    257458,
                    257468,
                    257485,
                    257499,
                    257519,
                    257531,
                    257557,
                    257567,
                    257623,
                    257633,
                    257677,
                    257788,
                    257804,
                    257838,
                    257915,
                    257921,
                    257942,
                    257947,
                    257973,
                    257985,
                    258091,
                    258200,
                    258209,
                    258252,
                    258254,
                    258297,
                    258317,
                    258326,
                    258333,
                    258339,
                    258348,
                    258390,
                    258488,
                    258513,
                    258517,
                    258587,
                    258595,
                    258622,
                    258737,
                    258751,
                    258757,
                    258782,
                    258814,
                    258876,
                    258931,
                    259024,
                    259033,
                    259043,
                    259049,
                    259073,
                    259105,
                    259136,
                    259141,
                    259199,
                    259218,
                    259294,
                    259306,
                    259316,
                    259319,
                    259325,
                    259329,
                    259363,
                    259366,
                    259378,
                    259484,
                    259532,
                    259586,
                    259610,
                    259628,
                    259632,
                    259704,
                    259718,
                    259719,
                    259778,
                    259779,
                    259782,
                    259810,
                    259812,
                    259850,
                    259868,
                    259894,
                    259904,
                    259912,
                    259918,
                    259919,
                    259944,
                    259955,
                    259956,
                    259977,
                    260049,
                    260058,
                    260068,
                    260090,
                    260118,
                    260130,
                    260156,
                    260193,
                    260230,
                    260243,
                    260247,
                    260250,
                    260281,
                    260319,
                    260329,
                    260347,
                    260351,
                    260362,
                    260367,
                    260396,
                    260433,
                    260451,
                    260457,
                    260475,
                    260512,
                    260530,
                    260536,
                    260552,
                    260572,
                    260651,
                    260687,
                    260689,
                    260704,
                    260715,
                    260719,
                    260726,
                    260729,
                    260739,
                    260752,
                    260780,
                    260811,
                    260818,
                    260842,
                    260849,
                    260850,
                    260871,
                    260874,
                    260875,
                    260886,
                    260888,
                    260905,
                    260916,
                    260985,
                    261009,
                    261021,
                    261158,
                    261175,
                    261193,
                    261200,
                    261207,
                    261229,
                    261232,
                    261242,
                    261244,
                    261250,
                    261261,
                    261262,
                    261280,
                    261281,
                    261285,
                    261301,
                    261348,
                    261351,
                    261364,
                    261365,
                    261382,
                    261384,
                    261396,
                    261419,
                    261463,
                    261479,
                    261484,
                    261511,
                    261538,
                    261568,
                    261585,
                    261619,
                    261629,
                    261671,
                    261715,
                    261724,
                    261753,
                    261780,
                    261846,
                    261861,
                    261874,
                    261900,
                    261913,
                    261924,
                    261925,
                    261928,
                    261940,
                    261959,
                    261982,
                    261997,
                    262030,
                    262036,
                    262044,
                    262071,
                    262084,
                    262090,
                    262094,
                    262109,
                    262126,
                    262130,
                    262137,
                    262171,
                    262184,
                    262186,
                    262197,
                    262213,
                    262241,
                    262252,
                    262269,
                    262297,
                    262308,
                    262324,
                    262466,
                    262495,
                    262507,
                    262626,
                    262647,
                    262693,
                    262715,
                    262749,
                    262828,
                    262841,
                    262850,
                    262865,
                    262954,
                    262958,
                    262979,
                    262999,
                    263106,
                    263158,
                    263196,
                    263304,
                    263324,
                    263346,
                    263393,
                    263444,
                    263459,
                    263511,
                    263534,
                    263537,
                    263570,
                    263583,
                    263609,
                    263666,
                    263672,
                    263720,
                    263751,
                    263764,
                    263770,
                    263797,
                    263829,
                    263850,
                    263899,
                    263935,
                    263938,
                    263959,
                    264194,
                    264260,
                    264295,
                    264313,
                    264318,
                    264341,
                    264368,
                    264421,
                    264438,
                    264462,
                    264538,
                    264562,
                    264569,
                    264577,
                    264594,
                    264599,
                    264621,
                    264631,
                    264645,
                    264654,
                    264717,
                    264754,
                    264808,
                    264829,
                    264830,
                    264870,
                    264928,
                    264945,
                    264955,
                    264967,
                    264995,
                    265003,
                    265004,
                    265006,
                    265012,
                    265013,
                    265030,
                    265037,
                    265106,
                    265115,
                    265139,
                    265151,
                    265152,
                    265161,
                    265163,
                    265302,
                    265306,
                    265312,
                    265316,
                    265339,
                    265396,
                    265419,
                    265460,
                    265505,
                    265521,
                    265541,
                    265555,
                    265557,
                    265561,
                    265575,
                    265607,
                    265612,
                    265656,
                    265679,
                    265695,
                    265723,
                    265778,
                    265799,
                    265802,
                    265879,
                    265883,
                    265885,
                    265889,
                    265900,
                    265945,
                    265955,
                    265989,
                    266012,
                    266049,
                    266062,
                    266070,
                    266089,
                    266096,
                    266116,
                    266121,
                    266140,
                    266144,
                    266146,
                    266154,
                    266166,
                    266169,
                    266187,
                    266267,
                    266274,
                    266296,
                    266297,
                    266303,
                    266319,
                    266331,
                    266380,
                    266389,
                    266419,
                    266426,
                    266434,
                    266447,
                    266480,
                    266559,
                    266611,
                    266633,
                    266646,
                    266661,
                    266732,
                    266733,
                    266734,
                    266773,
                    266776,
                    266785,
                    266807,
                    266813,
                    266837,
                    266885,
                    266919,
                    266998,
                    267004,
                    267021,
                    267036,
                    267093,
                    267094,
                    267105,
                    267153,
                    267160,
                    267174,
                    267195,
                    267203,
                    267219,
                    267222,
                    267227,
                    267261,
                    267273,
                    267278,
                    267326,
                    267376,
                    267382,
                    267395,
                    267417,
                    267424,
                    267430,
                    267457,
                    267467,
                    267516,
                    267520,
                    267549,
                    267578,
                    267581,
                    267582,
                    267593,
                    267601,
                    267609,
                    267634,
                    267645,
                    267710,
                    267714,
                    267791,
                    267813,
                    267816,
                    267833,
                    267881,
                    267892,
                    267925,
                    267934,
                    267938,
                    267953,
                    267978,
                    268020,
                    268048,
                    268088,
                    268090,
                    268094,
                    268105,
                    268109,
                    268118,
                    268129,
                    268146,
                    268160,
                    268162,
                    268166,
                    268202,
                    268209,
                    268232,
                    268272,
                    268282,
                    268375,
                    268380,
                    268401,
                    268411,
                    268436,
                    268445,
                    268447,
                    268473,
                    268511,
                    268534,
                    268554,
                    268614,
                    268624,
                    268631,
                    268648,
                    268653,
                    268697,
                    268706,
                    268712,
                    268727,
                    268762,
                    268763,
                    268764,
                    268773,
                    268776,
                    268780,
                    268782,
                    268808,
                    268812,
                    268832,
                    268853,
                    268865,
                    268933,
                    268985,
                    269030,
                    269060,
                    269073,
                    269078,
                    269083,
                    269097,
                    269111,
                    269135,
                    269144,
                    269166,
                    269185,
                    269187,
                    269250,
                    269255,
                    269272,
                    269278,
                    269313,
                    269325,
                    269347,
                    269368,
                    269370,
                    269389,
                    269474,
                    269498,
                    269517,
                    269552,
                    269603,
                    269654,
                    269656,
                    269664,
                    269681,
                    269686,
                    269688,
                    269708,
                    269718,
                    269754,
                    269759,
                    269760,
                    269778,
                    269787,
                    269796,
                    269829,
                    269833,
                    269834,
                    269847,
                    269850,
                    269854,
                    269883,
                    269891,
                    269898,
                    269899,
                    269901,
                    269946,
                    269947,
                    269957,
                    270008,
                    270027,
                    270092,
                    270102,
                    270122,
                    270127,
                    270136,
                    270139,
                    270144,
                    270213,
                    270227,
                    270251,
                    270253,
                    270325,
                    270333,
                    270363,
                    270373,
                    270388,
                    270423,
                    270446,
                    270464,
                    270489,
                    270513,
                    270540,
                    270544,
                    270547,
                    270578,
                    270588,
                    270620,
                    270655,
                    270667,
                    270682,
                    270721,
                    270755,
                    270759,
                    270760,
                    270772,
                    270778,
                    270796,
                    270805,
                    270807,
                    270824,
                    270826,
                    270861,
                    270883,
                    270893,
                    270909,
                    270911,
                    270915,
                    270943,
                    270957,
                    270966,
                    271094,
                    271133,
                    271147,
                    271162,
                    271180,
                    271204,
                    271226,
                    271228,
                    271239,
                    271258,
                    271277,
                    271279,
                    271283,
                    271291,
                    271303,
                    271310,
                    271327,
                    271331,
                    271352,
                    271362,
                    271371,
                    271382,
                    271394,
                    271400,
                    271403,
                    271421,
                    271447,
                    271449,
                    271481,
                    271484,
                    271498,
                    271508,
                    271538,
                    271550,
                    271559,
                    271560,
                    271570,
                    271572,
                    271579,
                    271595,
                    271596,
                    271599,
                    271638,
                    271662,
                    271668,
                    271671,
                    271676,
                    271681,
                    271691,
                    271749,
                    271759,
                    271766,
                    271772,
                    271787,
                    271809,
                    271812,
                    271864,
                    271869,
                    271916,
                    271936,
                    271974,
                    271980,
                    271988,
                    271991,
                    272000,
                    272001,
                    272014,
                    272057,
                    272072,
                    272083,
                    272086,
                    272115,
                    272116,
                    272128,
                    272136,
                    272179,
                    272237,
                    272257,
                    272265,
                    272276,
                    272278,
                    272357,
                    272391,
                    272393,
                    272403,
                    272417,
                    272421,
                    272432,
                    272437,
                    272459,
                    272468,
                    272503,
                    272537,
                    272556,
                    272561,
                    272584,
                    272609,
                    272648,
                    272684,
                    272705,
                    272724,
                    272746,
                    272755,
                    272769,
                    272781,
                    272795,
                    272858,
                    272888,
                    272916,
                    272965,
                    272974,
                    272986,
                    272987,
                    272989,
                    272990,
                    272994,
                    272995,
                    273009,
                    273013,
                    273017,
                    273038,
                    273046,
                    273054,
                    273084,
                    273128,
                    273129,
                    273139,
                    273152,
                    273153,
                    273164,
                    273167,
                    273193,
                    273203,
                    273209,
                    273216,
                    273224,
                    273230,
                    273231,
                    273248,
                    273275,
                    273284,
                    273286,
                    273304,
                    273321,
                    273326,
                    273334,
                    273345,
                    273358,
                    273365,
                    273392,
                    273397,
                    273405,
                    273425,
                    273447,
                    273463,
                    273475,
                    273492,
                    273515,
                    273517,
                    273521,
                    273534,
                    273541,
                    273599,
                    273637,
                    273641,
                    273648,
                    273675,
                    273689,
                    273721,
                    273772,
                    273797,
                    273819,
                    273838,
                    273954,
                    273962,
                    273964,
                    273972,
                    273995,
                    274000,
                    274024,
                    274025,
                    274057,
                    274110,
                    274189,
                    274304,
                    274308,
                    274320,
                    274387,
                    274390,
                    274410,
                    274471,
                    274483,
                    274532,
                    274533,
                    274628,
                    274633,
                    274774,
                    274863,
                    157541,
                    180249,
                    198280,
                    205291,
                    210172,
                    218667,
                    221052,
                    221867,
                    222360,
                    222864,
                    223022,
                    227240,
                    227961,
                    230604,
                    234690,
                    235812,
                    239085,
                    240310,
                    242375,
                    244385,
                    248353,
                    252189,
                    252242,
                    252920,
                    252981,
                    253118,
                    254194,
                    254833,
                    255265,
                    255447,
                    255954,
                    256221,
                    256575,
                    256697,
                    256735,
                    257123,
                    257277,
                    257280,
                    258125,
                    258487,
                    258576,
                    259280,
                    259612,
                    260313,
                    260547,
                    261532,
                    261893,
                    262053,
                    262396,
                    262414,
                    263153,
                    263656,
                    264550,
                    264643,
                    264938,
                    265095,
                    265245,
                    265777,
                    266066,
                    266123,
                    266253,
                    266512,
                    266562,
                    266944,
                    267011,
                    267075,
                    267136,
                    267940,
                    268222,
                    268291,
                    269121,
                    269146,
                    269813,
                    270189,
                    270417,
                    270894,
                    271037,
                    272059,
                    272407,
                    272920,
                    273051,
                    273360,
                    273569,
                    273871,
                    273968,
                    274014,
                    276521,
                    278999])))){
            Session::flash('error', 'You don\'t have permission to view the page');
            return redirect()->back();
        }

        
        
           $this->blackSoilApplications = array_merge($this->blackSoilApplications, [65229,
70073,
71223,
72156,
75447,
76382,
77700,
82078,
86366,
88342,
89846,
89984,
90813,
91050,
92416,
92610,
93618,
94023,
96911,
98832,
98896,
99977,
100418,
100650,
101712,
104003,
104597,
105298,
105498,
106330,
106574,
107801,
109909,
110707,
110709,
115041,
117004,
117566,
119701,
120857,
120872,
121209,
121746,
122509,
124633,
125855,
126092,
126492,
126856,
126884,
127208,
128162,
128653,
128785,
128936,
129606,
131174,
131521,
132737,
132970,
133506,
133795,
133837,
133838,
134597,
134682,
135339,
135889,
138621,
142278,
142656,
145282,
147240,
150281,
150780,
152846,
153473,
153508,
154184,
154753,
155239,
156968,
157345,
158302,
163069,
166103,
166366,
166814,
167959,
168180,
171718,
172629,
172922,
173050,
173090,
173719,
173814,
174190,
174687,
175091,
176212,
177016,
177568,
177876,
177896,
178909,
179188,
179336,
179585,
179991,
180249,
180750,
182155,
182292,
182310,
182843,
183259,
183365,
184162,
184238,
184569,
185119,
185310,
185535,
185563,
185725,
186220,
186653,
186975,
187094,
187098,
187101,
187123,
187150,
187227,
187304,
188105,
188178,
188541,
188559,
188679,
188806,
188825,
189002,
189067,
189432,
189574,
189752,
190160,
190560,
190704,
190765,
190870,
191176,
191419,
191692,
191909,
191954,
192572,
193180,
193356,
193731,
193890,
194734,
194967,
195162,
195180,
195337,
195388,
195412,
195428,
195620,
195791,
195852,
195986,
196009,
196589,
196658,
196721,
197060,
197368,
197391,
197570,
197646,
197719,
197860,
198090,
198220,
198247,
198470,
198471,
198971,
199212,
199478,
199564,
199618,
199999,
200066,
200254,
200335,
200715,
201470,
201479,
201517,
201659,
201671,
201730,
201847,
202161,
202220,
202598,
202666,
202769,
203026,
203192,
203212,
203303,
203621,
203859,
204015,
204016,
204267,
204655,
204969,
204975,
204996,
205058,
205218,
205291,
205371,
205516,
205635,
205768,
205785,
206002,
206022,
206041,
206375,
206380,
206382,
206663,
207330,
207331,
207411,
207425,
207468,
207482,
207511,
207540,
207582,
207633,
207698,
207710,
207785,
207819,
208353,
208481,
209195,
210067,
210103,
210146,
210411,
210427,
210542,
211157,
211221,
211703,
211942,
211963,
211984,
212217,
212319,
212498,
212528,
212579,
212638,
212667,
212892,
213066,
213195,
213212,
213311,
213319,
213413,
213572,
213961,
214087,
214114,
214153,
214389,
214395,
214469,
214509,
214547,
214666,
214792,
214818,
214855,
214904,
215073,
215122,
215240,
215243,
215286,
215404,
215411,
215532,
215632,
215703,
215705,
215743,
215795,
215855,
215872,
215969,
216027,
216230,
216408,
216951,
217019,
217167,
217326,
217390,
217741,
217801,
217861,
217923,
217941,
218144,
218177,
218286,
218559,
218667,
218806,
218813,
218847,
218951,
219197,
219252,
219269,
219987,
220008,
220073,
220157,
220209,
220228,
220235,
220370,
220594,
220741,
220790,
220810,
220876,
220915,
220975,
221137,
221215,
221273,
221299,
221329,
221358,
221398,
221441,
221557,
221583,
221605,
221805,
221835,
221972,
222203,
222372,
222496,
222634,
222709,
222771,
222854,
222930,
223130,
223136,
223219,
223260,
223280,
223461,
223479,
223481,
223558,
223629,
223797,
223954,
224037,
224150,
224216,
224274,
224284,
224639,
224671,
224684,
224765,
224799,
225059,
225118,
225132,
225350,
225367,
225370,
225380,
225509,
225532,
225590,
225645,
225653,
225689,
225758,
225783,
225799,
225810,
225823,
225896,
225904,
225909,
225910,
226165,
226190,
226205,
226245,
226282,
226415,
226445,
226570,
226600,
226820,
226852,
226896,
226920,
227002,
227101,
227111,
227141,
227147,
227176,
227206,
227312,
227313,
227359,
227407,
227479,
227511,
227512,
227534,
227691,
227704,
227706,
227834,
227838,
227854,
227864,
227882,
227991,
227993,
228072,
228193,
228390,
228500,
228552,
228553,
228569,
228575,
228588,
228619,
228645,
228649,
228675,
228792,
228845,
228917,
228929,
228991,
229046,
229073,
229143,
229187,
229266,
229386,
229389,
229404,
229521,
229535,
229572,
229574,
229659,
229662,
229718,
229761,
229840,
229904,
229928,
230003,
230055,
230061,
230091,
230098,
230145,
230146,
230193,
230197,
230362,
230401,
230505,
230519,
230539,
230568,
230712,
230720,
230753,
230754,
230803,
230856,
230886,
230939,
230965,
231002,
231037,
231142,
231170,
231193,
231194,
231242,
231258,
231297,
231378,
231448,
231450,
231484,
231496,
231558,
231707,
231867,
231869,
231899,
231913,
231918,
232014,
232106,
232121,
232141,
232159,
232235,
232333,
232359,
232436,
232472,
232503,
232605,
232625,
232769,
232786,
232799,
232824,
232876,
232954,
233006,
233016,
233122,
233310,
233338,
233375,
233383,
233390,
233397,
233452,
233471,
233487,
233498,
233561,
233618,
233795,
233878,
233898,
233903,
233904,
233915,
233918,
233944,
234008,
234054,
234315,
234417,
234472,
234531,
234548,
234766,
234925,
234993,
235145,
235157,
235236,
235300,
235301,
235429,
235461,
235468,
235658,
235702,
235752,
235806,
235818,
235883,
235991,
236074,
236124,
236132,
236138,
236195,
236264,
236277,
236295,
236325,
236591,
236606,
236858,
236876,
236909,
236940,
236971,
237011,
237027,
237092,
237143,
237173,
237350,
237371,
237580,
237679,
237686,
237771,
237807,
237841,
238063,
238092,
238191,
238200,
238305,
238318,
238493,
238569,
238605,
238699,
238864,
239020,
239052,
239057,
239115,
239154,
239244,
239627,
239635,
239743,
239744,
239765,
239796,
239834,
239840,
239851,
239895,
239896,
239926,
240007,
240105,
240123,
240349,
240529,
240536,
240652,
240799,
240935,
240963,
241032,
241064,
241133,
241140,
241157,
241191,
241204,
241214,
241251,
241298,
241404,
241421,
241543,
241591,
241674,
241744,
241793,
241886,
241900,
241931,
241933,
241984,
242061,
242100,
242138,
242172,
242266,
242372,
242439,
242533,
242577,
242601,
242631,
242663,
242747,
242795,
242848,
242914,
242981,
243123,
243171,
243185,
243205,
243397,
243411,
243429,
243455,
243457,
243458,
243491,
243556,
243586,
243592,
243634,
243653,
243655,
243661,
243663,
243667,
243674,
243726,
243760,
243779,
243826,
243894,
243925,
243959,
243968,
244094,
244196,
244198,
244199,
244315,
244359,
244385,
244418,
244427,
244459,
244611,
244680,
244687,
244753,
244781,
244809,
244937,
244980,
245047,
245049,
245050,
245090,
245091,
245099,
245108,
245193,
245208,
245232,
245244,
245272,
245360,
245401,
245448,
245469,
245562,
245593,
245628,
245673,
245698,
245763,
245863,
245879,
245891,
245924,
245939,
245989,
245993,
246046,
246048,
246111,
246132,
246152,
246165,
246187,
246241,
246322,
246325,
246339,
246360,
246380,
246432,
246448,
246503,
246507,
246547,
246610,
246690,
246892,
246904,
246922,
246939,
246994,
247023,
247033,
247148,
247171,
247175,
247189,
247202,
247243,
247253,
247261,
247306,
247332,
247354,
247386,
247403,
247462,
247495,
247514,
247515,
247547,
247571,
247584,
247601,
247641,
247706,
247716,
247729,
247860,
247863,
247946,
248096,
248101,
248102,
248113,
248120,
248151,
248173,
248396,
248449,
248464,
248481,
248492,
248538,
248563,
248590,
248610,
248658,
248662,
248674,
248675,
248686,
248699,
248737,
248800,
248801,
248902,
248904,
248916,
248952,
248960,
249035,
249039,
249056,
249110,
249173,
249201,
249211,
249274,
249305,
249319,
249321,
249343,
249376,
249432,
249442,
249601,
249640,
249643,
249701,
249740,
249759,
249812,
249889,
249917,
250093,
250109,
250133,
250197,
250269,
250318,
250353,
250404,
250449,
250477,
250497,
250583,
250605,
250639,
250683,
250725,
250744,
250863,
250873,
250934,
250952,
251142,
251171,
251290,
251309,
251330,
251338,
251360,
251368,
251382,
251487,
251495,
251512,
251554,
251587,
251615,
251624,
251626,
251630,
251646,
251667,
251750,
251759,
251801,
251858,
251899,
251929,
251955,
251988,
252193,
252222,
252280,
252293,
252331,
252374,
252424,
252468,
252528,
252560,
252571,
252586,
252589,
252703,
252720,
252735,
252783,
252844,
252845,
252847,
252909,
252961,
253121,
253122,
253147,
253207,
253277,
253279,
253287,
253309,
253314,
253329,
253388,
253410,
253416,
253565,
253587,
253622,
253634,
253657,
253659,
253669,
253678,
253693,
253705,
253757,
253809,
253831,
253841,
253913,
254031,
254061,
254064,
254131,
254163,
254167,
254173,
254194,
254360,
254365,
254376,
254424,
254454,
254476,
254495,
254510,
254535,
254598,
254599,
254642,
254707,
254843,
254898,
255036,
255051,
255133,
255135,
255153,
255159,
255160,
255166,
255230,
255265,
255437,
255452,
255487,
255534,
255555,
255653,
255760,
255806,
255834,
255837,
255846,
255889,
255971,
256022,
256067,
256116,
256151,
256181,
256301,
256399,
256402,
256405,
256524,
256560,
256575,
256659,
256660,
256747,
256806,
256823,
256850,
256897,
256919,
256922,
256962,
256988,
256999,
257059,
257088,
257154,
257156,
257222,
257262,
257277,
257358,
257393,
257400,
257405,
257431,
257454,
257462,
257517,
257518,
257575,
257590,
257596,
257650,
257661,
257664,
257823,
257844,
257860,
257878,
257947,
258065,
258083,
258108,
258122,
258312,
258342,
258346,
258348,
258352,
258358,
258364,
258390,
258435,
258457,
258565,
258585,
258599,
258614,
258627,
258702,
258720,
258724,
258765,
258788,
258814,
258855,
258919,
258931,
258934,
259080,
259145,
259162,
259269,
259283,
259284,
259294,
259295,
259344,
259367,
259371,
259403,
259479,
259537,
259546,
259598,
259601,
259603,
259612,
259621,
259628,
259644,
259665,
259694,
259696,
259719,
259725,
259745,
259751,
259779,
259782,
259784,
259788,
259797,
259841,
259885,
259888,
259894,
259920,
259923,
259973,
259974,
259977,
260011,
260017,
260048,
260081,
260085,
260118,
260125,
260133,
260135,
260156,
260174,
260189,
260207,
260210,
260235,
260236,
260244,
260258,
260310,
260335,
260374,
260396,
260452,
260457,
260473,
260514,
260523,
260541,
260558,
260590,
260635,
260636,
260660,
260662,
260689,
260704,
260716,
260717,
260726,
260739,
260741,
260778,
260841,
260865,
260875,
260922,
260988,
261007,
261084,
261218,
261249,
261250,
261259,
261267,
261294,
261307,
261322,
261331,
261344,
261351,
261362,
261365,
261402,
261493,
261501,
261563,
261568,
261606,
261611,
261651,
261654,
261722,
261762,
261764,
261822,
261823,
261847,
261871,
261884,
261893,
261932,
261936,
261948,
261976,
261989,
262001,
262011,
262041,
262044,
262055,
262071,
262096,
262126,
262149,
262181,
262197,
262213,
262225,
262241,
262266,
262287,
262324,
262332,
262373,
262414,
262429,
262449,
262506,
262513,
262534,
262544,
262565,
262589,
262626,
262685,
262695,
262702,
262717,
262737,
262749,
262760,
262765,
262795,
262810,
262833,
262852,
262932,
262934,
262954,
262997,
263050,
263080,
263108,
263148,
263158,
263161,
263162,
263195,
263213,
263215,
263229,
263263,
263267,
263325,
263336,
263350,
263361,
263385,
263402,
263403,
263433,
263444,
263470,
263486,
263487,
263511,
263522,
263525,
263527,
263537,
263556,
263585,
263592,
263593,
263655,
263656,
263666,
263668,
263675,
263683,
263699,
263706,
263710,
263776,
263791,
263835,
263836,
263938,
263942,
263971,
263985,
264186,
264195,
264198,
264222,
264224,
264272,
264279,
264282,
264283,
264311,
264327,
264332,
264336,
264395,
264398,
264401,
264407,
264419,
264430,
264454,
264530,
264539,
264585,
264611,
264635,
264665,
264666,
264674,
264678,
264733,
264742,
264765,
264787,
264788,
264810,
264819,
264825,
264829,
264830,
264893,
264898,
264937,
264938,
264954,
264957,
264967,
264968,
265016,
265030,
265032,
265040,
265090,
265105,
265150,
265165,
265210,
265223,
265226,
265240,
265241,
265248,
265250,
265253,
265273,
265306,
265331,
265336,
265361,
265413,
265416,
265422,
265449,
265451,
265468,
265478,
265504,
265507,
265511,
265512,
265517,
265529,
265530,
265538,
265555,
265574,
265575,
265587,
265602,
265626,
265627,
265630,
265650,
265651,
265667,
265681,
265695,
265731,
265755,
265777,
265781,
265797,
265809,
265814,
265840,
265842,
265856,
265861,
265895,
265897,
265928,
265942,
265945,
265947,
265948,
265965,
265969,
265973,
265990,
266007,
266009,
266010,
266012,
266013,
266034,
266035,
266080,
266089,
266090,
266184,
266224,
266239,
266257,
266283,
266301,
266330,
266343,
266345,
266380,
266382,
266389,
266408,
266417,
266433,
266447,
266462,
266465,
266487,
266489,
266514,
266515,
266562,
266571,
266577,
266583,
266586,
266606,
266626,
266634,
266654,
266661,
266668,
266677,
266680,
266731,
266751,
266754,
266760,
266777,
266793,
266807,
266824,
266837,
266844,
266899,
266919,
266944,
266960,
266968,
266991,
266993,
267011,
267025,
267054,
267063,
267079,
267080,
267084,
267112,
267123,
267127,
267136,
267141,
267155,
267158,
267173,
267188,
267197,
267200,
267220,
267231,
267261,
267286,
267302,
267318,
267334,
267336,
267351,
267384,
267387,
267419,
267423,
267425,
267430,
267441,
267455,
267491,
267520,
267549,
267556,
267564,
267578,
267582,
267585,
267598,
267609,
267638,
267641,
267687,
267690,
267710,
267716,
267722,
267726,
267742,
267754,
267770,
267771,
267791,
267813,
267881,
267882,
267885,
267888,
267938,
267947,
268018,
268105,
268129,
268151,
268160,
268199,
268200,
268204,
268206,
268212,
268213,
268222,
268237,
268270,
268277,
268281,
268285,
268299,
268308,
268315,
268347,
268387,
268436,
268505,
268531,
268542,
268545,
268554,
268555,
268558,
268567,
268621,
268624,
268648,
268658,
268660,
268663,
268683,
268739,
268805,
268809,
268853,
268863,
268915,
268933,
268949,
268970,
268975,
268985,
269003,
269040,
269083,
269084,
269097,
269102,
269144,
269149,
269173,
269186,
269190,
269196,
269208,
269230,
269231,
269232,
269245,
269259,
269273,
269296,
269305,
269311,
269313,
269317,
269319,
269329,
269349,
269355,
269360,
269371,
269394,
269410,
269419,
269440,
269448,
269510,
269528,
269551,
269552,
269569,
269571,
269591,
269600,
269615,
269619,
269642,
269701,
269746,
269760,
269762,
269763,
269764,
269768,
269771,
269792,
269794,
269796,
269799,
269803,
269818,
269829,
269850,
269854,
269869,
269883,
269899,
269920,
269924,
269932,
269946,
269949,
269950,
269952,
269957,
269962,
269965,
269974,
269990,
270016,
270027,
270061,
270084,
270092,
270102,
270108,
270113,
270137,
270150,
270176,
270210,
270234,
270251,
270252,
270265,
270272,
270279,
270281,
270311,
270314,
270325,
270326,
270333,
270346,
270363,
270383,
270388,
270412,
270458,
270513,
270522,
270526,
270535,
270540,
270544,
270557,
270558,
270578,
270592,
270632,
270638,
270644,
270655,
270661,
270684,
270714,
270720,
270722,
270725,
270739,
270746,
270751,
270760,
270764,
270771,
270807,
270824,
270826,
270872,
270876,
270893,
270894,
270901,
270925,
270926,
270934,
270936,
270941,
270943,
270957,
270966,
270983,
270997,
270998,
271017,
271042,
271059,
271094,
271190,
271195,
271216,
271222,
271226,
271235,
271250,
271258,
271261,
271278,
271290,
271303,
271327,
271362,
271371,
271394,
271403,
271409,
271412,
271420,
271436,
271447,
271449,
271457,
271486,
271498,
271537,
271554,
271570,
271572,
271579,
271599,
271605,
271615,
271633,
271638,
271662,
271666,
271681,
271721,
271728,
271745,
271766,
271771,
271793,
271799,
271803,
271834,
271838,
271861,
271864,
271869,
271920,
271921,
271931,
271934,
271953,
271960,
271980,
271984,
271988,
271997,
272068,
272086,
272089,
272098,
272101,
272115,
272128,
272136,
272143,
272166,
272181,
272206,
272237,
272239,
272240,
272259,
272278,
272323,
272349,
272360,
272364,
272365,
272366,
272368,
272380,
272394,
272407,
272417,
272468,
272485,
272490,
272516,
272530,
272540,
272559,
272605,
272609,
272610,
272622,
272626,
272632,
272669,
272674,
272676,
272705,
272752,
272753,
272770,
272800,
272829,
272861,
272865,
272883,
272897,
272914,
272917,
272955,
272984,
273003,
273004,
273020,
273027,
273029,
273034,
273036,
273045,
273047,
273049,
273054,
273085,
273091,
273094,
273108,
273125,
273140,
273161,
273162,
273185,
273195,
273252,
273265,
273273,
273282,
273283,
273295,
273307,
273343,
273347,
273349,
273355,
273360,
273427,
273439,
273452,
273463,
273488,
273492,
273494,
273497,
273516,
273517,
273535,
273554,
273556,
273558,
273568,
273573,
273597,
273623,
273646,
273648,
273656,
273675,
273683,
273690,
273695,
273697,
273742,
273744,
273755,
273763,
273765,
273777,
273778,
273779,
273800,
273838,
273852,
273853,
273856,
273868,
273871,
273872,
273877,
273882,
273899,
273910,
273915,
273925,
273928,
273930,
273938,
273972,
273978,
274014,
274028,
274037,
274057,
274065,
274066,
274098,
274111,
274131,
274133,
274142,
274152,
274154,
274171,
274189,
274191,
274203,
274209,
274216,
274220,
274233,
274262,
274309,
274324,
274326,
274330,
274333,
274335,
274340,
274351,
274382,
274416,
274423,
274437,
274455,
274469,
274528,
274536,
274537,
274545,
274550,
274596,
274629,
274631,
274645,
274667,
274674,
274709,
274726,
274729,
274735,
274744,
274794,
274807,
274818,
274827,
274851,
274872,
274873,
274888,
274897,
274902,
274912,
274915,
274927,
274943,
274947,
274960,
274962,
275007,
275013,
275020,
275023,
275032,
275044,
275054,
275066,
275072,
275073,
275097,
275106,
275109,
275110,
275124,
275125,
275138,
275146,
275150,
275156,
275159,
275171,
275183,
275196,
275211,
275224,
275233,
275236,
275260,
275263,
275284,
275315,
275317,
275318,
275321,
275328,
275348,
275394,
275395,
275401,
275402,
275403,
275422,
275424,
275433,
275458,
275461,
275468,
275471,
275481,
275491,
275493,
275550,
275553,
275554,
275570,
275578,
275579,
275581,
275599,
275607,
275611,
275620,
275633,
275646,
275649,
275652,
275704,
275721,
275746,
275755,
275767,
275769,
275771,
275778,
275781,
275785,
275788,
275825,
275828,
275832,
275843,
275847,
275855,
275876,
275886,
275890,
275892,
275922,
275936,
275939,
275946,
275951,
276002,
276024,
276025,
276030,
276033,
276035,
276043,
276048,
276053,
276078,
276082,
276090,
276100,
276110,
276131,
276132,
276133,
276152,
276163,
276180,
276217,
276224,
276242,
276250,
276255,
276293,
276294,
276310,
276312,
276327,
276330,
276343,
276345,
276379,
276385,
276396,
276407,
276410,
276416,
276420,
276428,
276436,
276440,
276457,
276465,
276484,
276501,
276530,
276535,
276537,
276538,
276555,
276581,
276595,
276609,
276616,
276618,
276625,
276630,
276637,
276640,
276661,
276662,
276684,
276694,
276720,
276728,
276741,
276744,
276753,
276760,
276770,
276783,
276785,
276789,
276792,
276835,
276843,
276846,
276870,
276879,
276888,
276895,
276915,
276931,
276939,
276940,
276949,
276952,
276956,
276966,
276969,
276991,
277011,
277034,
277036,
277043,
277046,
277050,
277068,
277075,
277077,
277085,
277092,
277093,
277115,
277124,
277140,
277147,
277173,
277184,
277188,
277193,
277208,
277217,
277232,
277235,
277254,
277285,
277289,
277298,
277299,
277300,
277307,
277308,
277335,
277343,
277348,
277356,
277357,
277365,
277371,
277380,
277388,
277390,
277413,
277414,
277423,
277426,
277429,
277439,
277445,
277451,
277452,
277460,
277470,
277475,
277485,
277521,
277524,
277528,
277550,
277555,
277568,
277571,
277577,
277594,
277603,
277616,
277654,
277664,
277666,
277678,
277682,
277689,
277702,
277704,
277754,
277771,
277772,
277782,
277783,
277788,
277790,
277802,
277804,
277809,
277817,
277829,
277844,
277846,
277869,
277894,
277895,
277897,
277899,
277911,
277913,
277917,
277924,
277937,
277949,
277950,
277956,
277979,
277982,
277996,
277997,
278007,
278034,
278035,
278047,
278048,
278056,
278067,
278082,
278093,
278104,
278127,
278133,
278134,
278147,
278175,
278182,
278204,
278211,
278251,
278252,
278259,
278264,
278282,
278284,
278287,
278294,
278336,
278344,
278353,
278360,
278364,
278366,
278372,
278387,
278391,
278394,
278424,
278433,
278441,
278459,
278496,
278534,
278543,
278557,
278559,
278571,
278576,
278595,
278596,
278599,
278621,
278631,
278632,
278635,
278639,
278655,
278679,
278683,
278696,
278707,
278709,
278710,
278730,
278758,
278763,
278764,
278770,
278777,
278780,
278789,
278802,
278857,
278865,
278869,
278887,
278892,
278895,
278909,
278954,
278975,
278977,
279009,
279045,
279096,
279098,
279108,
279113,
279118,
279122,
279128,
279158,
279225,
279227,
279240,
279243,
279248,
279264,
279315,
279323,
279327,
279369,
279372,
279390,
279409,
279411,
279420,
279446,
279453,
279455,
279492,
279580,
279587,
279592,
279615,
279617,
279621,
279632,
279638,
279714,
279741,
279742,
279755,
279762,
279771,
279774,
279794,
279802,
279811,
279813,
279833,
279842,
279856,
279864,
279870,
279871,
279909,
279966,
279972,
279985,
279998,
280009,
280019,
280041,
280057,
280085,
280087,
280088,
280094,
280125,
280148,
280149,
280153,
280169,
280172,
280199,
280209,
280211,
280247,
280251,
280256,
280275,
280296,
280331,
280339,
280361,
280380,
280405,
280439,
280457,
280468,
280522,
280528,
280538,
280543,
280570,
280589,
280623,
280642,
280650,
280651,
280677,
280742,
280745,
280750,
280795,
280818,
280834,
280839,
280845,
280856,
280873,
280905,
280910,
280927,
280944,
280947,
280950,
280952,
280960,
281014,
281018,
281022,
281036,
281043,
281045,
281065,
281092,
281104,
281106,
281110,
281120,
281124,
281156,
281183,
281207,
281220,
281237,
281246,
281302,
281303,
281328,
281330,
281333,
281411,
281427,
281433,
281447,
281462,
281503,
281523,
281528,
281550,
281560,
281573,
281578,
281594,
281604,
281606,
281644,
281649,
281652,
281658,
281730,
281743,
281753,
281768,
281769,
281770,
281772,
281792,
281820,
281821,
281823,
281825,
281867,
281878,
281880,
281951,
281954,
281986,
282054,
282077,
282078,
282085,
282093,
282095,
282113,
282118,
282125,
282131,
282144,
282171,
282190,
282210,
282239,
282263,
282282,
282284,
282303,
282312,
282396,
282398,
282431,
282454,
282477,
282493,
282495,
282496,
282510,
282542,
282549,
282577,
282588,
282594,
282604,
282608,
282659,
282668,
282679,
282684,
282686,
282698,
282709,
282714,
282726,
282746,
282807,
282833,
282863,
282878,
282885,
282905,
282937,
282970,
282977,
282985,
282986,
282994,
283017,
283041,
283058,
283072,
283073,
283077,
283091,
283103,
283118,
283165,
283214,
283218,
283227,
283238,
283252,
283254,
283266,
283279,
283283,
283286,
283289,
283290,
283303,
283314,
283315,
283316,
283320,
283334,
283346,
283361,
283372,
283379,
283388,
283399,
283414,
283429,
283439,
283454,
283463,
283466,
283468,
283509,
283522,
283523,
283556,
283585,
283595,
283628,
283651,
283668,
283691,
283693,
283710,
283714,
283722,
283733,
283739,
283751,
283757,
283794,
283804,
283805,
283829,
283830,
283831,
283844,
283882,
283893,
283898,
283923,
284007,
284012,
284019,
284024,
284033,
284041,
284048,
284051,
284056,
284060,
284065,
284068,
284078,
284138,
284141,
284155,
284161,
284171,
284176,
284188,
284192,
284196,
284224,
284231,
284246,
284278,
284288,
284299,
284303,
284311,
284340,
284352,
284404,
284432,
284527,
284542,
284595,
284607,
284613,
284624,
284654,
284686,
284725,
284781,
284832,
284895]);
        if (Auth::user()->user_type == _env('BLACKSOIL_USER_TYPE', 50) && !in_array($app->application_id, $this->blackSoilApplications)) {
            Session::flash('error', 'You don\'t have permission to view the page');
            return redirect()->to('/admin/consumer-applications');
        }

        ConsumerApplication::isApplicantType(true);
        $selected_categories = explode(',', Auth::user()->category);
        $data['sidebar'] = 'consumer-applications';
        //$this->updateMerchantRepresentativeDetails($id);
        $data['consumer_applications'] = ConsumerApplication::with('DisbursementOffersData','abflUTR','hypothecation_logs','activeOffer','avanse','avanseMandateStatus','avanseUTRStatus','checkmandate','co_applicant_company','trade_advance','proFormaInvoice','products.productOffer','payoutStatus.payoutLogs', 'CFPayoutRequestTransferStatus', 'CFPayoutDirectTransfer','userGeolocation', 'digital_sign', 'lender', 'merchant', 'merchant_location', 'bank_details', 'creditReport', 'foir', 'merchant.merchant_category_many', 'emi', 'company', 'application_element.collection_executive', 'calls', 'disbursement','telecom_data','finBitData','cibilReportBorrower','cibilReportCoBorrower','equifax_documents', 'coapp_equifax_documents','agency', 'application_element.merchant_center', 'electricity_bill','application_additional')->find($id);
        // edit to avoid accessing non merchant applications for merchant 2.0
        if (Auth::check() && Auth::user()->user_type == UserTypes::$merchant_v2) {
            $anchorMerchantForRows = DB::select("SELECT id from merchant where anchor_merchant_id = ?", [Auth::user()->merchant_id]);
            $anchorMerchantFor = array_map(function($row) { return $row->id; }, $anchorMerchantForRows);
            array_push($anchorMerchantFor, Auth::user()->merchant_id);
            if(!in_array($data['consumer_applications']->merchant_id, $anchorMerchantFor)){
                Session::flash('error', 'You don\'t have permission to view the page');
                return redirect()->back();
            }
        }
        
        if(!isset($data['consumer_applications']->id)){
            \Session::flash('error', 'Application does not exist');
            return redirect()->to('/admin/consumer-applications');
        }

        $visible_stages = $this->getStatusVisibilityPermissions();
        if(is_array($visible_stages) && count($visible_stages) > 0 && !in_array($data['consumer_applications']->state, $visible_stages)) {
            Session::flash('error', 'You don\'t have permission to view the page');
            return redirect()->back();
        }

        if(isset($data['consumer_applications']->digital_sign) && count($data['consumer_applications']->digital_sign)){
            $isSigned = ConsumerApplicationFiles::where('consumer_application_id', $id)->where('file_type', 'loan_agreement_esign')->first(['id']);

            if(!isset($isSigned->id)){
                if ($data['consumer_applications']->co_applicant_name && count($data['consumer_applications']->digital_sign) == 2){
                    (new FrontController())->sendEsignUpdate($id, true);
                }else if(!$data['consumer_applications']->co_applicant_name){
                    (new FrontController())->sendEsignUpdate($id, true);
                }
            }
        }

        if (isset($data['consumer_applications']->creditReport) && count($data['consumer_applications']->creditReport)) {
            $data['consumer_applications']->creditReport[0]->dpd = (new ScoreCard(new Request()))->getAverageDPDs($data['consumer_applications']->foir, $data['consumer_applications']->creditReport[0]->applicant_type);
            if(isset($data['consumer_applications']->creditReport[1])){
            $data['consumer_applications']->creditReport[1]->dpd = (new ScoreCard(new Request()))->getAverageDPDs($data['consumer_applications']->foir, $data['consumer_applications']->creditReport[1]->applicant_type);
            }
        }




        //$data['is_applicant']=0;
        //$data['is_co_applicant']=0;
        //$personal_loan_data = FOIR::where('application_id', $id)->where('AccountType','Personal Loan')->get(['applicant_type','DateOpened']);


        if($data['consumer_applications']->lender_id == AvanseServices::$lender_id && isset($data['consumer_applications']->avanse) && $data['consumer_applications']->avanse){
            $data['avanse'] = $this->getAvanseData($id);
        }

        if($data['consumer_applications']->foir) {
            foreach ($data['consumer_applications']->foir as $foirData) {
                if($foirData->AccountType == 'Personal Loan') {
                    $difference = (Carbon::parse($data['consumer_applications']->created_at)->diffInDays($foirData->DateOpened));
                    if ($difference <= 90) {
                        if ($foirData->applicant_type == 1) {
                            $data['is_applicant'] = 1;
                        }
                        if ($foirData->applicant_type == 2) {
                            $data['is_co_applicant'] = 1;
                        }
                    }
                }
            }
        }


        //default nach properties
        /*$nach = (new Nach(new Request()))->getDefaultNachProperties($data['consumer_applications'], $id);
        if(count($data['consumer_applications']->mandateMany) < 2){
            $data['consumer_applications']['mandateMany'] = $nach;
        }*/
        //$courier = (new CouriersController(new Request()));
        //$data['couriers'] = $courier->getCourier($id, 2);
        //$data['nach_status'] = $courier->NACHStatus($id);
        //
        $data['consumer_applications']->status_logs = (new StatusLogs())->getLogs($id);
        $data['consumer_applications']->kyc_verified = (new StatusLogs())->getKycVerified($id);
        $data['consumer_applications']->process_logs = (new StatusLogs())->getProcessLogs($id);
        $data['consumer_applications']->bureau_report = $this->getBureauReport($id, $data['consumer_applications']);
        // dd($data['consumer_applications']);
        //$data['consumer_applications_file'] = ConsumerApplicationFiles::where('consumer_application_id', $id)->get();
        // dd($data['consumer_applications_file']);
        // foreach ($data['consumer_applications_file'] as $key => $value) {
        //     dd($value->file_type);
        // }
        // status
        $i = 0;
        if (\Auth::user()->user_type >= 5) {
            array_unshift($this->statusarray['pre approved'], 'approved');
            array_unshift($this->statusarray['pre approved'], 'cf approved');
            array_unshift($this->statusarray['cf approved'], 'approved');
            array_unshift($this->statusarray['waiting for decision'], 'approved');
            array_unshift($this->statusarray['disbursement checklist done'], 'ready for disbursement');
            array_unshift($this->statusarray['disbursement checklist done'], 'disbursement query');
            array_unshift($this->statusarray['ready for disbursement'], 'disbursed');
            array_unshift($this->statusarray['cancelled'], 'disbursed');
        }

        $statusCheck = array();
        /*if ($data['consumer_applications']->state == 'waiting for decision' && ((Auth::user()->user_type == 'operation') || Auth::user()->user_type == 'sales') && $data['consumer_applications']->emi) {
            $grade = new GradeController(new Request());
            $_grade = $grade->ApprovalCheck($id);
            if (empty(array_filter($_grade->getOutput()))) {
                $statusCheck = $this->statusarray[$data['consumer_applications']->state];
                array_unshift($statusCheck, 'approved');
            }
        }*/

        if ($data['consumer_applications']->state == "cancellation in-process") {
            $previous_status = StatusLogs::where('application_id', $data['consumer_applications']->id)->orderBy('created_at', 'desc')->skip(1)->take(1)->get();
            if (isset($previous_status[0]->status)) {
                array_unshift($this->statusarray['cancellation in-process'], $previous_status[0]->status);
            }
        }
        if (_env('JSON_BRE_ACTIVE')) {
            $autoApproval = (new JSONBREController())->getJsonApprovalLogs($id);
        } 
        if (!_env('JSON_BRE_ACTIVE') || (isset($autoApproval) && empty($autoApproval))) { // to display old applications approval logs
            $autoApproval = $this->getAutoApprovalDetails($id);
        }
        if($autoApproval) {
            $data['autoApproval'] = $autoApproval;
        }
        if ($autoPreApproval = $this->getAutoPreApproval($id)) {
            $data['autoPreApproval'] = $autoPreApproval;
        }

        if ($autoDocumentStatus = $this->getAutoDocumentRuleLog($id)) {
            $data['autoDocumentStatus'] = $autoDocumentStatus;
        }

        if ($autoRejectLogs = $this->getAutoRejectLog($id)) {
            $data['autoRejectLogs'] = $autoRejectLogs;
        }

        $current_status = strtolower($data['consumer_applications']->state);

        $statusData = ($statusCheck) ? $statusCheck : $this->statusarray[$current_status];

        $showOptions = $this->getPermissions();
        $statusData = array_filter(array_map(function ($status) use ($showOptions) {
            return (array_search($status, $showOptions)) !== false ? $status : '';
        }, $statusData));

        $data['consumer_applications']->statusarray = $statusData;
        $data['consumer_applications']->statusgroup = $this->arraygroup[$current_status];
        //end
        $data['state_list'] = StateModel::get(['name', 'code', 'id']);
        $data['users'] = User::where('user_type', '>=', 5)->where('email', 'like', '%@creditfair.in%')->whereNull('deleted_at')->get(['id', 'name', 'user_type']);
        $bnpl_merchants = BNPL::getMerchants();

        $auth_merchant_id = null;
        if(Auth::check() && Auth::user()->merchant_id){
            $auth_merchant_id = Auth::user()->merchant_id;
        }

        $query = Merchant::select('id', 'merchant_name', 'category_id') 
            ->where('status', 'active')
            ->where('is_guest_active', 1);

        if ($is_bnpl) {
            $query->whereIn('id', $bnpl_merchants);
        } else {
            $query->whereNotIn('id', $bnpl_merchants);

            $filtered_categories = array_filter($selected_categories);
            if (!empty($filtered_categories)) {
                $query->whereIn('category_id', $filtered_categories);
            }
        }

        if ($auth_merchant_id) {
            $query->where('id', $auth_merchant_id);
        }

        $data['merchants'] = $query
            ->with(['merchant_category_many:id,name']) 
            ->get();

        $data['merchantLocation'] = MerchantLocation::get();
        $data['linkedin_link'] = Checklist::where('application_id', $id)->first(['linkedin']);

        $data['additional_docs_list'] = explode(",", $data['consumer_applications']->additional_docs_list);

        // $data['fileLists'] = ConsumerApplicationFiles::where('consumer_application_id', $id)->groupBy('file_type')->get(['file_type']);

        // dd($data['merchantLocation'][0]->id);

        /*$data['files'] = ConsumerApplicationFiles::with('user','UtilityValidation')->where('consumer_application_id', $id)->get();

        $callsLogs = CallLogs::with('picked_by','received_by')->where('_id', $id)->where('id_type','application_id')->where(function ($query){
            $query->Where('recording', '!=', '')
            ->orWhere('status','in-progress');
        })->get(['id', '_id', 'user_id', 'recording', 'purpose', 'created_at','to','status']);
        foreach ($callsLogs as $indexCall => $callData) {
            $data['files'][] = $callData;
        }*/

        //$data['merchant_list'] = Merchant::where('status', 'active')->where('is_guest_active', 1)->get(['merchant_name as name', 'id', 'category_id']);
        $data['application_status'] = array_map('ucfirst', array_keys($this->arraygroup));;

        $current_status = strtolower($data['consumer_applications']['state']);
        $data['application_status'] = $this->statusarray[$current_status];
        array_unshift($data['application_status'], $current_status);
        $data['page'] = 'edit';
        $docsCheck = Input::has('next-status') && isset($this->DocsStatus[Input::get('next-status')]) ? $this->DocsStatus[Input::get('next-status')] : [];
        $request = new Request();
        $request->attributes->add(['check' => $docsCheck, 'data' => ['application_id' => $id], 'bot' => true]);
        $docsCheck = $this->checkValidations($request);
        $data['docsCheck'] = $docsCheck->getData();
        $data['industries'] = ScoreCard::$industryCreditFair;
        $data['profession'] = ScoreCard::$professionTypeCreditFair;
        //$data['negativeProfile'] = NegativeProfile::get();
        $data['disable_edits'] = (in_array($data['consumer_applications']->state, $this->statusreversearray['approved'])) ? 1 : 0;
        if (in_array($data['consumer_applications']->state, ['closed', 'nach registered'])) {
            $data['disable_edits'] = 2;
        }

        if ($data['consumer_applications']->digital_sign && isset($data['consumer_applications']->digital_sign[0])) {
            if ($data['consumer_applications']->digital_sign[0]->isagreementsigned) {
                $data['isagreementsigned'] = 1;
            }
        }

        /*if(isset($data['consumer_applications']->payoutStatus) && isset($data['consumer_applications']->payoutStatus->status) && $data['consumer_applications']->payoutStatus->status != 'SUCCESS') {
            $payout = new PayoutAPI(new Request(['id' => $id]));
            $payout->getDisbursementStatus($id);
        }*/

        /*if ($negativeArea = $this->getNegativeAreaList($data)) {
            $data['isNegativeArea'] = $negativeArea;
        }*/
        $data['advisors'] = $data['users'];//User::where('user_type', '>=', 5)->whereNull('deleted_at')->get(['id', 'name']);
        //$data['communication_logs'] = $this->getCustomerCommunications($id);
        $data['advisor_logs'] = AdvisorLogs::with('previous', 'current', 'action_by')->where('application_id', $id)->get();


        $this->fetchCallDetails($data['consumer_applications'], $request);

        if ($data['consumer_applications']->disbursement) {
            $disbursements = new DisbursementController($request);
            $data['consumer_applications']->disbursement = $disbursements->getDisbursementAdjustment($data['consumer_applications']->disbursement);
        }

        if ($data['consumer_applications']->application_element && $data['consumer_applications']->application_element->collection_advisor && $data['consumer_applications']->permanent_address_pincode) {
            if (Session::has('Change_Collection_Executive|-22')) {
                $userIds = getAvaibleAdvisor($data['consumer_applications']->permanent_address_pincode);
                if ($userIds && is_array($userIds)) {
                    $data['available_advisor'] = User::whereIn('id', $userIds)->get(['id', 'name']);
                }
            }
        }

        $epfData = (new EPFUANLookup())->getUANByApplication($id);
        $epfFailureLogs = (new EpfFailureLog())->getEpfFailureLogsbyApplication($id);
        $data['epf'] = $epfData['epf'];
        $data['epf_failure_logs_applicant'] = $epfFailureLogs['epf'];
        $data['epfCoApplicant'] = $epfData['epfCoApplicant'];
        $data['epf_failure_logs_coapplicant'] = $epfFailureLogs['epfCoApplicant'];

        $gstReports = GSTPANData::where('application_id', $id)
                            ->orderBy('created_at', 'desc') // Get latest first
                            ->get();

        // Filter collection for Applicant (Type 1)
        $applicantReport = $gstReports->where('type', 1)->first();
        if ($applicantReport) {
            $data['gstReport'] = $applicantReport;
        }

        // Filter collection for Co-Applicant (Type 2)
        $coApplicantReport = $gstReports->where('type', 2)->first();
        if ($coApplicantReport) {
            $data['gstReportCoApplicant'] = $coApplicantReport;
        }

        $data['telecome_data'] = TelecomData::where('mobile_number', wall_decrypt($data['consumer_applications']->mobile_number))->first(['id']);
        if($data['consumer_applications']->user_id) {
            $referredData = User::where('id', $data['consumer_applications']->user_id)->first(['referred_by']);
            if(isset($referredData->referred_by) && $referredData->referred_by) {
                $data['referred_by'] = User::where('code', $referredData->referred_by)->first(['id', 'name']);
            }
        }

        //Corona
        if(isset($data['consumer_applications']->current_address_pincode) && !empty($data['consumer_applications']->current_address_pincode) || isset($data['consumer_applications']->permanent_address_pincode) && !empty($data['consumer_applications']->permanent_address_pincode)){
            $is_hotspot = CoronaHotspot::whereIn('pincode', [$data['consumer_applications']->current_address_pincode, $data['consumer_applications']->permanent_address_pincode])->first(['id']);

            if(isset($is_hotspot->id) && !empty($is_hotspot->id)) {
                $data['hotspotted_area'] = 1;
            }
        }

        try {
            $tallyLeaderExist = TallyJobs::where('application_id', $id)->where('payload', 'like', '%LEDGER%')->first(['id']);
            if (!isset($tallyLeaderExist->id)) {
                $data['tallyLeaderExist'] = 1;
            }
        }catch (\Exception $e){

        }

        $data['case_reviewed'] = 0;
        if($data['consumer_applications']->state=='rejected'){
            $is_case_review_requested = Comments::where('application_id', $id)->whereIn('request_review', [0,1])->get();
            //$is_case_reviewed = Comments::where('application_id', $id)->where('request_review', 1)->first();
            if( (count($is_case_review_requested) == 1 && $is_case_review_requested[0]->request_review == 0) || (count($is_case_review_requested) > 1)){
                $data['case_reviewed'] = 1;
            }
        }

        $data['is_pin_set'] = 1;
        $consumer_application_states = Pincode::whereIn('pincode', [$data['consumer_applications']->current_address_pincode, $data['consumer_applications']->permanent_address_pincode, $data['consumer_applications']->co_applicant_address_pincode])->get(['state', 'pincode']);
        $saved_states = [$data['consumer_applications']->current_address_pincode => $data['consumer_applications']->current_address_state, $data['consumer_applications']->permanent_address_pincode => $data['consumer_applications']->permanent_address_state, $data['consumer_applications']->co_applicant_address_pincode => $data['consumer_applications']->co_applicant_address_state];

        $i = 0;

        foreach($consumer_application_states as $state){

            if(isset($state->state) && !empty($state->state)){
                $state_name = ucwords(strtolower($state->state));

            if( isset($saved_states[$state->pincode]) && !empty($saved_states[$state->pincode]) )   {
                if ($state_name != $saved_states[$state->pincode]) {
                    $data['is_pin_set'] = 0;
                    break;
                }
                }
            }

            $i++;
        }

        if($data['consumer_applications']->user_id) {
            try {
                $s3 = Storage::disk('s3');
                if ($s3->exists('/info/' . $data['consumer_applications']->user_id)) {
                    $data['View_User_Info'] = 1;
                }
            }catch (\Exception $e){

            }
        }

        if(count($data['consumer_applications']['creditReport']) > 0) {
            $this->isInternal = true;
            $this->sendReturnStatus = true;
            $creditReport = $this->getCibilReport($id, 1);
            if (!$creditReport instanceof RedirectResponse && !empty($creditReport) && $creditReport !== 'failed' && isset($creditReport['report_data']['sch:ReportData']['sch:AccountSummary']['sch:TotalBalanceAmount'])) {
                $data['consumer_applications']['creditReport'][0]['loan_outstanding'] = $creditReport['report_data']['sch:ReportData']['sch:AccountSummary']['sch:TotalBalanceAmount'];
            } else {
                $data['consumer_applications']['creditReport'][0]['loan_outstanding'] = '0';
            }
        }

        $data['distance'] = $this->getDistanceBetweenLocations($data['consumer_applications']);
        $data['bureauReport'] = $this->bureauReportMatchedData($data['consumer_applications']);

        $unapproved_pin_codes = $this->getUnapprovedPincodes($id);
        $data['approver_data_exist'] = $unapproved_pin_codes['approver_data_exist'];
        $data['unapproved_pin_codes'] = $unapproved_pin_codes['unapproved_pin_codes'];
        $data['upc'] = $unapproved_pin_codes['unapproved_pin_codes'];
        $data['upa'] = $unapproved_pin_codes['full_approved_address'];
        $approverData = ApproverData::with('user')->where('application_id',$id)->first();
        $data['approver_name']= ($approverData && $approverData->user) ? $approverData->user->name : '';
        if(Auth::check()){
            if(Auth::user()->is_manager == 1){
                $data['isManager'] = Auth::user()->is_manager;
            }
        }

        $data['lenderAccess'] = $this->getLenderPermissions();
        $data['is_current_address_pincode'] = $unapproved_pin_codes['is_current_address_pincode'];

        if ($data['consumer_applications']->lender_id == AvanseServices::$lender_id){
            $data['lenderSpecificDocs'] = AvanseServices::getDocumentsLists();
        }

        $data['decisionData'] = (new TestingController())->getAutoDecisionRulesData($id);

        $data['inverter_list'] = $this->inverterList();

        $data['service_provider_list'] = $this->serviceProviderList();

        $data['panel_list'] = $this->panelList();


        $aadhar_link_check_with_comm_number_initial_date = $this->releaseDates['aadhar_mobile_check'];
        $aadhar_link_check_with_aadhar_number_initial_date = $this->releaseDates['aadhar_mobile_check_v2'];

        // $approvedLog = StatusLogs::where('application_id', $id)->where('status', 'waiting for decision')->orderBy('created_at', 'asc')->first(['created_at']);
        $approvedLog = StatusLogs::where('application_id', $id)
            ->where(function ($query) {
                $query->where('status', 'waiting for decision')
                    ->orWhere('status', 'approved');
            })
            ->orderByRaw("CASE 
                            WHEN status = 'waiting for decision' THEN 1 
                            WHEN status = 'approved' THEN 2 
                        END, created_at ASC")
            ->first(['created_at', 'status']);

        $aadharLinkCheckReleaseDate = Carbon::parse($aadhar_link_check_with_comm_number_initial_date);
        if ($approvedLog && isset($data['consumer_applications']->application_additional)) {
            $approvedDate = Carbon::parse($approvedLog->created_at);
            $number_type = "comm_number";
            if ($aadharLinkCheckReleaseDate->gt($approvedDate)) {
                $data['aadharMobileLinkCommNumber'] = null;
                $data['coAadharMobileLinkCommNumber'] = null;
            }else{
                $data['aadharMobileLinkCommNumber'] = $this->getAadharMaskedMobile($id, $data['consumer_applications']->application_additional->linked_status, 1, $number_type);
                $data['coAadharMobileLinkCommNumber'] = $this->getAadharMaskedMobile($id, $data['consumer_applications']->application_additional->co_linked_status, 2, $number_type);
            }
        }
        unset($aadharLinkCheckReleaseDate);

        $aadharLinkCheckReleaseDate = Carbon::parse($aadhar_link_check_with_aadhar_number_initial_date);
        if ($approvedLog && isset($data['consumer_applications']->application_additional)) {
            $approvedDate = Carbon::parse($approvedLog->created_at);
            $number_type = "aadhar_linked_mobile";
            if ($aadharLinkCheckReleaseDate->gt($approvedDate)) {
                $data['aadharMobileLinkAadharNumber'] = null;
                $data['coAadharMobileLinkAadharNumber'] = null;
            }else{
                $data['aadharMobileLinkAadharNumber'] = $this->getAadharMaskedMobile($id, $data['consumer_applications']->application_additional->linked_mobile_to_aadhar_status, 1, $number_type);
                $data['coAadharMobileLinkAadharNumber'] = $this->getAadharMaskedMobile($id, $data['consumer_applications']->application_additional->coapp_linked_mobile_to_aadhar_status, 2, $number_type);
            }
        }
        $data['statusBeforeApproved'] = $this->statusBeforeApproved;


        $document_type = "consent_logs";

        $data['consent_log_exists'] = $this->checkAnyDocumentExists($id, $document_type);


        if(isset($data['consumer_applications']->application_element->type_of_customer) && $data['consumer_applications']->application_element->type_of_customer == $this->solar_category['atta_chakki']){
            $request = new Request([
                'application_id' => $data['consumer_applications']->id,
                'distance_in_km' => 5,
            ]);
            $data['previous_location_cases'] = $this->getCaseWiseData($request);
        }
        $data['application_id'] = $id;
        $data['kw_check'] = true;
        $flag = $this->checkKWValidation($id);
        if(!$flag){
            $data['kw_check'] = false;
        }

        $ckyc_data = DecentroCkyc::where('application_id', $id)->count();
        if($ckyc_data >0){
            $data['ckyc_status'] = 1;
        }
        $modifiedDisbursementRequests = [];

        $disbursementRequests = DisbursementRequests::where("application_id",$id)->whereNull('deleted_at')->orderBy('created_at','desc')->get();
        foreach ($disbursementRequests as $requests) {
            // Retrieve the advisor's name using the advisor ID
            $advisor = User::find($requests->requested_by);

            // Check if advisor exists
            if ($advisor) {
                $requests->advisor_name = $advisor->name;
                $modifiedDisbursementRequests[] = $requests;
            } else {
                $requests->advisor_name = "";
                $modifiedDisbursementRequests[] = $requests;
            }
        }

        $data['discoms_data'] = $this->getDiscomsData();
        // Return the modified disbursementRequests variable with advisor names appended
        $data['disbursementRequests'] = $modifiedDisbursementRequests;
    /*try{
        $credit_report_on = CreditReport::where('application_id', $id)->first(['id']);

        if (isset($credit_report_on->id)) {
            $creditline = new CreditLine(new Request(['id' => $id]));
            $creditDatainsert = $creditline->getCreditData();
            $credit_report = CreditReport::find($credit_report_on->id);
            $credit_report->ml_loan_amount = $creditDatainsert['max_loan_amount_to_sanction_basis_ml'] ? $creditDatainsert['max_loan_amount_to_sanction_basis_ml'] : null ;
            $credit_report->ml_eligible_emi_amount = $creditDatainsert['eligible_emi_amount_ml'] ? $creditDatainsert['eligible_emi_amount_ml'] : null ;
            $credit_report->foir_loan_amount = $creditDatainsert['max_loan_amount_to_sanction_basis_foir'] ? $creditDatainsert['max_loan_amount_to_sanction_basis_foir'] : null ;
            $credit_report->foir_eligible_emi_amount = $creditDatainsert['eligible_emi_amount_basis_foir'] ? $creditDatainsert['eligible_emi_amount_basis_foir'] : null ;
            $credit_report->save();
        }
    }catch(\Exception $e){

    }*/
        $data['consumer_applications']['app_consent'] = 0;
        $data['consumer_applications']['co_app_consent'] = 0;

        if(isset($data['consumer_applications']->proFormaInvoice)){
            $data['insurance_collection_method'] = $data['consumer_applications']->proFormaInvoice->insurance_premium_by_merchant;
        }else{
            $data['insurance_collection_method'] = $data['consumer_applications']->merchant->insurance_collection_method;
        }

        // Check applicant consent
        $appConsent = ConsumerApplicationFiles::where([
            ['consumer_application_id', $data['consumer_applications']->id],
            ['file_type', 'consent_logs'],
            ['applicant_type', 1]
        ])->exists();

        if (!$appConsent) {
            $data['consumer_applications']['app_consent'] = 1;
        }
        // Check co-applicant consent only if co-applicant exists
        if (!empty($data['consumer_applications']->co_applicant_name)) {
            $coAppConsent = ConsumerApplicationFiles::where([
                ['consumer_application_id', $data['consumer_applications']->id],
                ['file_type', 'co_app_consent_logs'],
                ['applicant_type', 2]
            ])->exists();

            if (!$coAppConsent) {
                $data['consumer_applications']['co_app_consent'] = 1;
            }
        }

        if(in_array(strtolower($data["consumer_applications"]->state), ['disbursed', 'nach registered', 'closed'])){
            $latestFiles = DB::select("Select file_type from consumer_application_files where consumer_application_id = ? and deleted_at is null group by file_type", [$id]);
            $systemFileTypes = DB::select("Select file_type from user_documents");
            $data['other_documents'] = array_diff(array_column($latestFiles, 'file_type'), array_column($systemFileTypes, 'file_type'));
            $data['other_documents'] = array_values(array_filter($data['other_documents'], function($value) {
                return $value !== 'bank_statement_1';
            }));
            $data['application_files'] = array_column($latestFiles, 'file_type');
        }

        $data['sanctioned_amount_with_insurance'] = EMICalculation::getLoanAmountWithInsuranceAmount($id);
        $data['revocation_list'] = $this->getRevocationList($id);
        $hash = new Hashids('Creditfair by CS', 20);
        $data['hashed_id'] = $hash->encode($id);
        $data['risk_based_interest_rate'] = RiskBasedInterestRate::where('application_id', $id)->orderBy('created_at', 'desc')->first(['id', 'new_interest_rate', 'is_excluding_pf', 'offer_id']);
        $data['json_bre_response'] = DB::selectOne("SELECT id from bre_logs where application_id = ? and response != 'null' order by created_at desc",[$id]);
        
        $net_loan_amount = 1;
        $offerId = $data['consumer_applications']->offer_id ?? null;
        if (!empty($offerId)) {
            $active_offer = MerchantOffers::where('id', $offerId)->first();

            if ($active_offer) {
                $loan_amount = $data['consumer_applications']->loan_amount ?? 0 ;
                $autoBRE = new autoBRE();
                $net_loan_amount = $autoBRE->calculateNetLoanAmount($loan_amount, $active_offer);
            }
        }

        $data['checkers'] = User::where('credit_approval_limit', '>=', $net_loan_amount)
                                ->whereNull('deleted_at')
                                ->get(['id', 'name', 'credit_approval_limit']);
        $creditReport = $data['consumer_applications']['creditReport'][0] ?? null;
        $data['credit_score'] = $creditReport->Score ?? '';
        $data['applicant_foir'] = isset($creditReport->foirIncludingCFEMI)
            ? number_format($creditReport->foirIncludingCFEMI, 2) . '%'
            : '';

        $data['caseReviewPendingCount'] = 0;
        if (strtolower($data['consumer_applications']->state) === 'disbursement query') {
            $data['caseReviewPendingCount'] = CaseReviewRequest::getPendingCount($id);
        }

        $data['hasPendingDisbDeviation'] = false;
        if (isset($data['consumer_applications']->statusarray) && in_array('ready for disbursement', array_map('strtolower', $data['consumer_applications']->statusarray))) {
            $data['hasPendingDisbDeviation'] = ApplicationDeviation::hasPendingDisbDeviation($id);
        }

        // Duplicate applicant/co-applicant indicator 
        $duplicateInfo = $this->isExistingCustomer($id, false);
        $data['is_duplicate'] = $duplicateInfo ? true : false;
        $data['applicant_duplicate'] = $data['is_duplicate'] && (bool) preg_match('/\[(?!Co-App)[^\]]+\]/', $duplicateInfo);
        $data['coapplicant_duplicate'] = $data['is_duplicate'] && strpos($duplicateInfo, '[Co-App') !== false;
        $data['duplicate_info'] = $duplicateInfo;

        if($is_bnpl){
            return view('admin.bnpl-application.edit', $data);
        }else{
            return view('admin.consumer-application.edit_v1', $data);
        }

    }

    public function getRevocationList($id){
        $lists = RevocationList::where('application_id', $id)->get(['phone' ,'status']);

        $revocationList = [];
        foreach($lists as $list){
            $revocationList[$list->phone] = $list->status;
        }

        return $revocationList;
    }

    public function checkAnyDocumentExists($id, $document_type){

        $files = ConsumerApplicationFiles::where('consumer_application_id', $id)->where('file_type', $document_type)->whereNull('deleted_at')->orderBy('created_at','DESC')->get(['id']);

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


    public function exportAutoDecisionRuleData($iteration){
        $payload[] = [
            'payload' => json_encode(['user_id' => Auth::user()->id, 'iteration' => $iteration]),
            'from' => 'export_auto_decision_data',
            'application_id' => 0,
            'available_at' => Carbon::now()->toDateTimeString(),
            'created_at' => Carbon::now()->toDateTimeString()
        ];

        $job = new Jobs();
        $job->insertQueue($payload);
        return 'Report will be sent on mail shortly';
    }

    public function getDistanceBetweenLocations($application){
        try {
            $userGeolocationCurrent = UserGeolocation::where('_id', $application->id)->where('id_type', 'application_id')->where('service','current')->whereNull('deleted_at')->first(['id', 'latitude', 'longitude']);
            $data = [];
            $current_lat = null;
            $current_lng = null;

            $merchant = Merchant::where('id', $application->merchant_id)->first(['id', 'longitude', 'latitude']);
            if(!isset($userGeolocationCurrent->id)) {
                $address = ['address' => $application->current_address_line_1.' '.$application->current_address_landmark.', '.$application->current_address_city.' '.$application->current_address_state.' '.$application->current_address_pincode, 'pincode' => $application->current_address_pincode];
                $geoData = [];
                $geoLatLng  = $this->getGeocodingDataFromAddress($address);
                if(!empty($geoLatLng)){
                    $geoData    = ['lat' => $geoLatLng['lat'], 'lng' => $geoLatLng['lng'], 'pincode' => $geoLatLng['pincode'], 'applicant_type' => 1, 'address_type' => 'current'];
                }
                if($geoData) {
                    $this->saveUserGeolocation($application, ['applicant_type' => 1, 'applicant_id' => $application->applicant_id, 'id_type' => 'application_id', 'service' => $geoData['address_type'], 'longitude' => $geoData['lng'], 'latitude' => $geoData['lat'], 'pincode' => $geoData['pincode']]);
                    $current_lat = $geoData['lat'];
                    $current_lng = $geoData['lng'];
                }
            }else{
                $current_lat = $userGeolocationCurrent->latitude;
                $current_lng = $userGeolocationCurrent->longitude;
            }


            if(isset($merchant->id) && $merchant->latitude && $merchant->longitude){
                $data['address_dealer_merchant'] = ['distance' => $this->distance($current_lat, $current_lng, $merchant->latitude, $merchant->longitude, 'K')]; //M - Miles, K - Kilometers, N - Nautical Miles
            }

            $userGeolocation = UserNearestStations::where('_id', $application->id)->where('applicant_id', $application->applicant_id)->where('applicant_type', 1)->where('id_type', 'application_id')
                ->first(['id','latitude', 'longitude', 'nearest_station']);

            if(isset($userGeolocation->id)){
                $data['address_metro'] = ['distance' => $this->distance($current_lat, $current_lng, $userGeolocation->latitude, $userGeolocation->longitude, 'K'), 'Location' => $userGeolocation->nearest_station];
            }else {
                if($nearestLocation = $this->getNearByMetro($current_lat, $current_lng)){
                    $this->saveNearestStations($application, ['latitude' => $nearestLocation['lat'], 'longitude' => $nearestLocation['lng'], 'applicant_id' => $application->applicant_id, 'applicant_type' => 1, 'id_type' => 'application_id', 'name' => $nearestLocation['name'], 'response' => $nearestLocation['response']]);
                    $data['address_metro'] = ['distance' => $this->distance($current_lat, $current_lng, $nearestLocation['lat'], $nearestLocation['lng'], 'K'), 'Location' => $nearestLocation['name']];
                }
            }


            if($application->application_element && $application->application_element->center_id){
                $merchantLocation = MerchantLocation::where('id', $application->application_element->center_id)->first(['id','location', 'state']);
                if(isset($merchantLocation->id)) {
                    $address = ['address' => $merchantLocation->location . ' ' . $merchantLocation->state, 'pincode' => preg_match_all('/(?<!\d)\d{6}(?!\d)/', $merchantLocation->location, $match) ? $match[0] : ''];
                    $geoLatLng = $this->getGeocodingDataFromAddress($address);
                    if($geoLatLng) {
                        $geoData = ['lat' => $geoLatLng['lat'], 'lng' => $geoLatLng['lng'], 'pincode' => $geoLatLng['pincode'], 'applicant_type' => 1, 'address_type' => 'current'];

                        $this->saveUserGeolocation($application, ['applicant_type' => 1, 'applicant_id' => $application->application_element->center_id, 'id_type' => 'merchant_location_id', 'service' => $geoData['address_type'], 'longitude' => $geoData['lng'], 'latitude' => $geoData['lat'], 'pincode' => $geoData['pincode'], '_id' => $application->application_element->center_id]);

                        $centre_lat = $geoLatLng['lat'];
                        $centre_lng = $geoLatLng['lng'];

                        $data['address_dealer_center'] = ['distance' => $this->distance($current_lat, $current_lng, $centre_lat, $centre_lng, 'K')]; //M - Miles, K - Kilometers, N - Nautical Miles
                    }
                }
            }
            return $data;
        } catch (\Exception $e) {
            (new \App\Slack(new Request(['title' => 'Latitude Longtidue distance error', 'fields' => ['error' => $e->getMessage(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString(), 'application_id' => $application->id]])))->send();
            return [];
        }
    }

    public function saveNearestStations($application, $data)
    {
        if ($data['latitude'] && $data['longitude']) {
            $userGeolocation = UserNearestStations::where('_id', $application->id)->where('applicant_type', $data['applicant_type'])->where('id_type', $data['id_type'])
                ->first(['id']);

            if (!isset($userGeolocation->id)) {
                UserNearestStations::insert([
                    '_id' => isset($data['_id']) ? $data['_id'] : $application->id,
                    'id_type' => $data['id_type'],
                    'applicant_id' => isset($data['applicant_id']) ? $data['applicant_id'] : (isset($application->applicant_id) ? $application->applicant_id : 0),
                    'applicant_type' => $data['applicant_type'],
                    'latitude' => $data['latitude'],
                    'longitude' => $data['longitude'],
                    'response' => json_encode($data['response']),
                    'nearest_station' => $data['name'],
                    'created_at' => Carbon::now()->toDateTimeString()
                ]);
            } else {
                UserNearestStations::where('id', $userGeolocation->id)->update(['latitude' => $data['latitude'], 'longitude' => $data['longitude']]);
            }
        }
    }

    public function distance($lat1, $lon1, $lat2, $lon2, $unit) {

        $theta = $lon1 - $lon2;
        $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
        $dist = acos($dist);
        $dist = rad2deg($dist);
        $miles = $dist * 60 * 1.1515;
        $unit = strtoupper($unit);

        if ($unit == "K") {
            return round($miles * 1.609344, 2).' KM';
        } else if ($unit == "N") {
            return round($miles * 0.8684, 2);
        } else {
            return round($miles, 2);
        }
    }

    public function getBureauReport($id, $application){
        $files = ConsumerApplicationFiles::where('consumer_application_id', $id)->whereNull('deleted_at')->whereNotNull('bureau_report_type')->whereNotNull('bureau_report_score')->orderBy('created_at','DESC')->get(['consumer_application_id', 'bureau_report_type', 'bureau_report_score']);

        $score = [];
        foreach ($files as $file){
            if ($file->bureau_report_score) {
                $score[$file->bureau_report_type][] = $file->bureau_report_score;
            }
        }

        $bureau = new Bureau(new Request());

        if($application->cibilReportBorrower){
            foreach ($application->cibilReportBorrower as $cibilReportBorrower){
                if ($cibilReportBorrower) {

                    $bandRange = $bureau->getScore(['band' => $cibilReportBorrower->band]);

                    $mKey = 'CIBIL Applicant (Avanse)';
                    if($cibilReportBorrower->remarks){
                        $mKey .= '<br/><b>Remark:</b> '.$cibilReportBorrower->remarks;
                    }
                    if($cibilReportBorrower->remarks){
                        $mKey .= '<br/><b>Total Obligation:</b> '.$cibilReportBorrower->totalObligation;
                    }
                    if($cibilReportBorrower->remarks){
                        $mKey .= '<br/><b>Past30DaysEnq:</b> '.$cibilReportBorrower->past30daysEnq;
                    }
                    if($cibilReportBorrower->remarks){
                        $mKey .= '<br/><b>Past12MonthsEnq:</b> '.$cibilReportBorrower->past12MonthsEnq;
                    }
                    if($cibilReportBorrower->remarks){
                        $mKey .= '<br/><b>Past24MonthsEnq:</b> '.$cibilReportBorrower->past24MonthsEnq;
                    }
                    if($cibilReportBorrower->remarks){
                        $mKey .= '<br/><b>Description:</b> '.$cibilReportBorrower->description;
                    }
                    if($cibilReportBorrower->remarks){
                        $mKey .= '<br/><b>DPD30_12Months:</b> '.$cibilReportBorrower->dpd30_12month;
                    }
                    if($cibilReportBorrower->remarks){
                        $mKey .= '<br/><b>DPD90_12Months:</b> '.$cibilReportBorrower->dpd90_12month;
                    }

                    $bandValue = $cibilReportBorrower->band;
                    if(isset($bandRange['min'])){
                        $bandValue .= ' (Band Range: '.$bandRange['min'].'-'.$bandRange['max'].')';
                    }

                    $score[$mKey][] = $bandValue;
                }
            }
        }

        if($application->cibilReportCoBorrower){
            foreach ($application->cibilReportCoBorrower as $cibilReportCoBorrower){
                if ($cibilReportCoBorrower) {

                    $bandRange = $bureau->getScore(['band' => $cibilReportCoBorrower->band]);

                    $mKey = 'CIBIL Co-Applicant (Avanse)';
                    if($cibilReportCoBorrower->remarks){
                        $mKey .= '<br/><b>Remark:</b> '.$cibilReportCoBorrower->remarks;
                    }
                    if($cibilReportCoBorrower->remarks){
                        $mKey .= '<br/><b>Total Obligation:</b> '.$cibilReportCoBorrower->totalObligation;
                    }
                    if($cibilReportCoBorrower->remarks){
                        $mKey .= '<br/><b>Past30DaysEnq:</b> '.$cibilReportCoBorrower->past30daysEnq;
                    }
                    if($cibilReportCoBorrower->remarks){
                        $mKey .= '<br/><b>Past12MonthsEnq:</b> '.$cibilReportCoBorrower->past12MonthsEnq;
                    }
                    if($cibilReportCoBorrower->remarks){
                        $mKey .= '<br/><b>Past24MonthsEnq:</b> '.$cibilReportCoBorrower->past24MonthsEnq;
                    }
                    if($cibilReportCoBorrower->remarks){
                        $mKey .= '<br/><b>Description:</b> '.$cibilReportCoBorrower->description;
                    }
                    if($cibilReportCoBorrower->remarks){
                        $mKey .= '<br/><b>DPD30_12Months:</b> '.$cibilReportCoBorrower->dpd30_12month;
                    }
                    if($cibilReportCoBorrower->remarks){
                        $mKey .= '<br/><b>DPD90_12Months:</b> '.$cibilReportCoBorrower->dpd90_12month;
                    }

                    $bandValue = $cibilReportCoBorrower->band;
                    if(isset($bandRange['min'])){
                        $bandValue .= ' (Band Range: '.$bandRange['min'].'-'.$bandRange['max'].')';
                    }

                    $score[$mKey][] = $bandValue;
                }
            }
        }


        return $score;
    }


    public function creditLineInputs(Request $request){
        $data = [];

        if($request->get('search')) {

            $keyword = $request->get('search');
            $application = ConsumerApplication::where(function ($query) use ($keyword) {
                $query->where('name', 'like', '%' . $keyword . '%')
                    ->orWhere('email', 'like', '%' . $keyword . '%')
                    ->orWhere('id', 'like', '%' . $keyword . '%')
                    ->orWhere('co_applicant_name', 'like', '%' . $keyword . '%')
                    ->orWhere('co_applicant_email', 'like', '%' . $keyword . '%')
                    ->orWhere('co_applicant_mobile_number', 'like', '%' . $keyword . '%')
                    ->orWhere('mobile_number', 'like', '%' . $keyword . '%');
            })->first(['id']);

            $creditLine = new CreditLine(new Request(['id' => $application->id]));
            $data['creditLimit'] = $creditLine->getCreditData();
        }
        return view('admin.credit_line_inputs', $data);
    }

    public function fetchCallDetails($data, Request $request)
    {
        if (count($data->calls)) {
            foreach ($data->calls as $call) {
                if (isset($call->sid)) {
                    $request->merge(['sid' => $call->sid, 'id' => $call->id]);
                    $exotelService = new ExotelServices($request);
                    $exotelService->getCall();
                }
            }
        }
    }

    public function foirDelete(Request $request)
    {
        if ($request->has('id')) {
            FOIR::where('id', $request->get('id'))->update(['deleted_by' => Auth::user()->id]);
            FOIR::where('id', $request->get('id'))->delete();
            return \response()->json(['status' => 'OK']);
        }

        return \response()->json(['status' => 'FAIL', 'message' => 'something went wrong']);
    }

    public function getAccountStatement($id)
    {
        $frontController = new FrontController();
        return $frontController->getStatement($id);
    }

    public function getNegativeAreaList($data)
    {
        $address['current'] = isset($data['consumer_applications']->current_address_pincode) ? $data['consumer_applications']->current_address_pincode : ((isset($data['current_pincode']) ? $data['current_pincode'] : ''));
        // $address['permanent'] = isset($data['consumer_applications']->permanent_address_pincode) ? $data['consumer_applications']->permanent_address_pincode : ((isset($data['permanent_pincode']) ? $data['permanent_pincode'] : ''));
        // $address['co_applicant'] = isset($data['consumer_applications']->co_applicant_address_pincode) ? $data['consumer_applications']->co_applicant_address_pincode : ((isset($data['co_applicant_pincode']) ? $data['co_applicant_pincode'] : ''));
        $address['installation'] = isset($data['consumer_applications']->application_element->installation_address_pincode) ? $data['consumer_applications']->application_element->installation_address_pincode : ((isset($data['installation_pincode']) ? $data['installation_pincode'] : ''));
        $pinList = [];
        $levels = [];
        $areaList = [];
        foreach ($address as $keyName => $address_line) {
            if ($address_line) {
                if (!in_array($address_line, $pinList)) {
                    $negative_list = NegativeArea::where('pincode', $address_line)->first();
                    if ($negative_list) {
                        $pinList[] = $address_line;
                        $levels[] = $negative_list->level;
                        $negative_list->type = $keyName;
                        $areaList[] = $negative_list;
                    }
                }
            }
        }

        if ($levels) {
            $negativeArea = new \stdClass();
            $negativeArea->level = min($levels);
            $negativeArea->list = $areaList;
            return $negativeArea;
        }
        return false;
    }

    public function getAutoRejectLog($id){
        $keyMap = ['MIN_MAX_SCORE' => 'Score', 'MIN_AGE' => 'AGE', 'MAX_AGE' => 'AGE', 'MONTHLY_INCOME' => 'Monthly Income',
            'APPROVED_PINCODE' => 'Approved Pincode', 'NEGATIVE_AREA' => 'Negative Area', 'DPD' => 'DPD', 'ACCOUNT_STATUS' => 'Account Status',
            'PRINCIPAL_WRITTEN_OFF_AMOUNT' => 'Principal Written Off Amount', 'TOTAL_PAST_DUES' => 'Past Dues Amount', 'KEYWORD' => 'Keyword',
            'NACH_BOUNCE' => 'EMI/Nach Bounce'];
        
        // Fetch only the latest auto-rejection log for applicant and co-applicant each
        $logs = AutoRejectLogs::where('application_id', $id)->orderBy('created_at','desc')->orderBy('applicant_type','asc')->get(['reason', 'failure_details', 'applicant_type'])->unique('applicant_type');
        
        if (empty($logs)) return false;

        $finalOutput = [];
        foreach ($logs as $log) {
            $failureDetails = json_decode($log->failure_details, true);
            
            if ($log->applicant_type == 1) {
                // Applicant Section
                $roleMessages = $this->parseRejectionRoleLogs($failureDetails, $keyMap);
                if (!empty($roleMessages)) {
                    $finalOutput[] = "<div class='mb-3'><span class='m-badge m-badge--warning m-badge--wide'>Applicant</span> " . implode(', ', $roleMessages) . "</div>";
                }
            } else {
                // Co-applicant Sections
                $isStructured = (isset($failureDetails['income']) || isset($failureDetails['signing']) || isset($failureDetails['general']));
                
                if ($isStructured) {
                    foreach (['signing', 'income', 'general'] as $role) {
                        if (isset($failureDetails[$role]) && !empty($failureDetails[$role])) {
                            $roleMessages = $this->parseRejectionRoleLogs($failureDetails[$role], $keyMap);
                            if (!empty($roleMessages)) {
                                $label = "Co-applicant" . ($role != 'general' ? " for {$role}" : "");
                                $content = implode(', ', $roleMessages);
                                
                                if ($role == 'income') {
                                    $finalOutput[] = "<div class='mb-3'><span class='m-badge m-badge--warning m-badge--wide'>{$label}</span> <details style='padding-top:5px; display:inline-block; vertical-align:top;'><summary style='cursor:pointer; outline:none;'> <small>(Click to expand)</small></summary><div class='mt-2' style='padding-left:10px; border-left:2px solid #ebedf2;'>" . $content . "</div></details></div>";
                                } else {
                                    $finalOutput[] = "<div class='mb-3'><span class='m-badge m-badge--warning m-badge--wide'>{$label}</span>: " . $content . "</div>";
                                }
                            }
                        }
                    }
                } else {
                    // Legacy/Flat Co-applicant Logs
                    $roleMessages = $this->parseRejectionRoleLogs($failureDetails, $keyMap);
                    if (!empty($roleMessages)) {
                        $finalOutput[] = "<div class='mb-3'><span class='m-badge m-badge--warning m-badge--wide'>Co-applicant</span> " . implode(', ', $roleMessages) . "</div>";
                    }
                }
            }
        }

        return !empty($finalOutput) ? implode('', $finalOutput) : false;
    }

    /**
     * Helper to parse a set of rejection rules into messages
     */
    private function parseRejectionRoleLogs($failureLogs, $keyMap) {
        $rejectLogs = [];
        if (empty($failureLogs)) return $rejectLogs;
        foreach($failureLogs as $key => $result) {
            if (!isset($keyMap[$key])) {
                $rejectLogs[] = $key;
                continue;
            }
            
            $displayKey = $keyMap[$key];
            // Normalize result to object
            $result = (object)$result;
            $rulesRaw = $result->rules;
            
            // Extract the rule object/value
            if (is_array($rulesRaw)) {
                // For sequential arrays (like DPD), take the first element
                // For associative arrays (like MIN_MAX_SCORE), use the whole array
                $rule = isset($rulesRaw[0]) ? (object)$rulesRaw[0] : (object)$rulesRaw;
            } elseif (is_object($rulesRaw)) {
                $rule = $rulesRaw;
            } else {
                $rule = $rulesRaw; // Scalar value (string/int)
            }
            
            $message = '';
            switch ($key) {
                case 'DPD':
                    if (isset($rule->value)) {
                        $message = "{$rule->value} days in the last {$rule->months} months {$rule->operator} {$rule->tradelines} tradelines";
                    }
                    break;
                case 'KEYWORD':
                    $accountNumber = [];
                    if (isset($result->records) && is_array($result->records) && isset($result->records[0])) {
                        foreach($result->records[0] as $accounts) {
                            $explodedString = explode(' ', $accounts);
                            $accountNumber[] = $explodedString[0];
                        }
                    }
                    $accountNumberString = !empty($accountNumber) ? implode(", ", array_unique($accountNumber)) : '';
                    $acctMessage = !empty($accountNumberString) ? ": Account Number - {$accountNumberString}" : "";
                    if (is_object($rule) && isset($rule->value)) {
                        $message = "{$rule->value} in the last {$rule->months} months {$rule->operator} {$rule->tradelines} tradelines{$acctMessage}";
                    } else {
                        $message = $acctMessage;
                    }
                    break;
                case 'ACCOUNT_STATUS':
                case 'PRINCIPAL_WRITTEN_OFF_AMOUNT':
                    if (is_object($rule)) {
                        $message = "{$rule->value} in the last {$rule->months} months";
                    }
                    break;
                case 'TOTAL_PAST_DUES':
                    if (is_object($rule)) {
                        $message = "{$rule->value} for {$rule->account_type} in the last {$rule->months} months";
                    }
                    break;
                case 'NACH_BOUNCE':
                    if (is_object($rule)) {
                        $message = "Bounce {$rule->value} {$rule->operator} in the last {$rule->months} months";
                    }
                    break;
                case 'MIN_MAX_SCORE':
                    $max = isset($rule->max) ? $rule->max : (isset($rulesRaw['max']) ? $rulesRaw['max'] : '');
                    $min = isset($rule->min) ? $rule->min : (isset($rulesRaw['min']) ? $rulesRaw['min'] : '');
                    $message = "Max: {$max} & Min: {$min}";
                    break;
                case 'MAX_AGE':
                case 'MIN_AGE':
                    $val = is_object($rule) ? ($rule->scalar ?? json_encode($rule)) : $rule;
                    $label = $key == 'MAX_AGE' ? 'Max Age' : 'Min Age';
                    $message = "{$label}: {$val}";
                    break;
                default:
                    $message = is_string($rule) ? $rule : json_encode($rule);
            }
            $rejectLogs[] = ($displayKey == 'Approved Pincode' || $displayKey == 'Negative Area') ? "<b>$displayKey</b>" : "<b>$displayKey</b> - <code>$message</code>";
        }
        return $rejectLogs;
    }

    public function getAutoDocumentRuleLog($id)
    {
        $autoDocumentStatus = DocumentRuleLog::where('application_id', $id)->orderBy('created_at', 'desc')->first();
        if ($autoDocumentStatus) {
            if ($autoDocumentStatus->net_disbursement) {
                return 'Net Disbursement';
            } else if ($autoDocumentStatus->monthly_income) {
                return 'Monthly Income';
            } else if ($autoDocumentStatus->employee_status) {
                return 'Employee Status';
            } else if ($autoDocumentStatus->loan_amount) {
                return 'Loan Amount';
            } else if ($autoDocumentStatus->foir) {
                return 'FOIR';
            } else if ($autoDocumentStatus->negative_profile) {
                return 'Negative Profile';
            } else if ($autoDocumentStatus->collateral_loan) {
                return 'Collateral Loan';
            } else if ($autoDocumentStatus->negative_area) {
                return 'Negative Area';
            } else if ($autoDocumentStatus->score) {
                return 'Score';
            }
            $consumerElement = ConsumerApplicationElement::where('application_id', $id)->first(['auto_document_rule_id']);
            if (isset($consumerElement->auto_document_rule_id) && $consumerElement->auto_document_rule_id) {
                return 'Auto Document Mail Sent';
            }
        }
        return false;
    }

    public function getAutoPreApproval($id)
    {
        $preApprovalLog = PreApprovalLog::where('application_id', $id)->orderBy('created_at', 'desc')->first();
        if ($preApprovalLog) {
            if ($preApprovalLog->employee_status) {
                return 'employee_status';
            } else if ($preApprovalLog->past_dues) {
                return 'past_dues';
            } else if ($preApprovalLog->foir) {
                return 'foir';
            } else if ($preApprovalLog->cf_foir) {
                return 'cf_foir';
            } else if ($preApprovalLog->score) {
                return 'score';
            } else if ($preApprovalLog->loan_amount) {
                return 'loan_amount';
            } else if ($preApprovalLog->tenure) {
                return 'tenure';
            } else if ($preApprovalLog->gold) {
                return 'Gold Loan';
            } else if ($preApprovalLog->monthly_income) {
                return 'monthly_income';
            } else if ($preApprovalLog->age) {
                return 'age';
            } else if ($preApprovalLog->age_at_last_emi) {
                return 'age_at_last_emi';
            } else if ($preApprovalLog->three_year) {
                return 'three_year';
            } else if ($preApprovalLog->residence_status) {
                return 'residence_status';
            } else if ($preApprovalLog->case_type) {
                return 'case_type';
            } else if ($preApprovalLog->account_type) {
                return 'account_type';
            } else if ($preApprovalLog->term_loan) {
                return 'term_loan';
            } else if ($preApprovalLog->above_three) {
                return 'above_three';
            } else if ($preApprovalLog->dpd) {
                return 'DPD';
            }
            return 'Pre Approved';
        }
        return false;
    }

    public function getAutoApproval($id)
    {
        $approvalCheck = Approval::where('application_id', $id)->get()->toArray();
        if (isset($approvalCheck[0])) {
            $approvalCheck = end($approvalCheck);
            unset($approvalCheck['application_id']);
            unset($approvalCheck['id']);
            unset($approvalCheck['created_at']);
            unset($approvalCheck['updated_at']);
            unset($approvalCheck['status']);
            if (empty(array_filter($approvalCheck))) {
                $statusLgos = StatusLogs::where('application_id', $id)->where('status','approved')->where('user_id', 107)->first(['id']);
                if (isset($statusLgos->id)) {
                    return 'Approved';
                }
            } else {
                foreach ($approvalCheck as $key => $value) {
                    if($key == 'error' || $key == 'epf_verification'){
                        if($value == 1){
                            $result = $approvalCheck['reason'] ? $approvalCheck['reason'] : '';
                            if($result) {
                                return (isset($result)) ? 'Application not approved because of ' . $result : $key;
                            }
                        }
                    }
                        if ($value != 0) {
                            return $this->getApprovalTerms($key, $value);
                        }
                }
            }
        }
        return false;
    }

    public function getAutoApprovalDetails($id)
    {
        $approvalCheck = ApprovalStatusLog::where('application_id', $id)->orderBy('created_at', 'desc')->first();
        if (isset($approvalCheck->id)) {
            return ApprovalStatusLog::with('rule')->where('application_id', $id)->where('request_batch_id', $approvalCheck->request_batch_id)->get();
        }
        return false;
    }

    public function getApprovalTerms($check, $value)
    {
        switch ($check) {
            case 'negativeProfile':
                $key = 'Negative Profile';
                break;
            case 'checkDuplicates':
                $key = 'Duplicate case';
                break;
            case 'aboveThreeYear':
                $key = 'DPD < 15 days in CLOSED tracks with closure date > 3 years prior';
                break;
            case 'score':
                $key = 'Score is ' . $value;
                break;
            case 'threeYear':
                $key = 'DPD < 10 days across all LIVE loan tracks (including credit cards) and tracks closed within last 3 years';
                break;
            case 'pastDues':
                $key = 'Past Dues';
                break;
            case 'termLoan':
                $key = 'Loan tracks should contain ATLEAST 1 TERM LOAN with vintage > 12 months';
                break;
            case 'caseType':
                $key = 'Case Type';
                break;
            case 'is_credit_card':
                $key = 'Credit Card';
                break;
            case 'credit_limit_five_times':
                $key = 'Credit Limit (Five times of our EMI)';
                break;
            case 'AccountType':
                $key = 'Gold Loan';
                break;
            case 'foir':
                $key = 'FOIR';
                break;
            case 'cf_foir':
                $key = 'CF FOIR';
                break;
            case 'rejected':
                $key = 'Application is rejected or aborted once';
                break;
            case 'address_status':
                $key = 'Current address in not Owned';
                break;
            case 'downpayment':
                $key = 'Downpayment is 0';
                break;
            case 'negative_area':
                $key = 'Address is negative list';
                break;
        }

        return (isset($key) && $key) ? 'Application not approved because of ' . $key : $check;
    }

    public function getVerificationScript(Request $request)
    {

        $application = ConsumerApplication::with('merchant', 'emi', 'offer', 'application_element','proFormaInvoice')->where('id', $request->get('id'))->first();

        if($application->application_element && ($request->get('user_type') == 'Reference 1' || $request->get('user_type') == 'Reference 2')){
            $name = $request->get('user_type') == 'Reference 1' ? $application->application_element->reference_name_1 : ($request->get('user_type') == 'Reference 2' ? $application->application_element->reference_name_2 : '') ;
            $script = "Dear <b>" . $name . ",</b><br/>Do you know <b>".$application->name."</b> ? How do you know him/her ?<br/>We wanted to inform you that he/she has applied for a Loan with us & has given your contact for Reference.<br/>Are you ok with it ?<br/>Thank you!";
        } else if ($application->merchant && $application->emi && $application->merchant->merchant_category) {
            $amount = 0;
            $advance_emi = '-';
            $interest_rate = '-';
            $advance_amount = 0;
            $dob = '-';
            $name = $request->get('user_type') == 'Applicant' ? $application->name : $application->co_applicant_name;
            $dob = $request->get('user_type') == 'Applicant' ? $application->dob : $application->co_applicant_dob;


            if ($application->emi) {
                $advance_type = $application->offer->advance_type == 'percentage' ? '%' : ($application->offer->advance_type == 'fixed_amount' ? 'Amount' : 'EMI');

                $advance_emi = $application->emi->advance_emi . ' ' . $advance_type;
                if ($advance_type == 'Amount') {
                    $advance_emi = '₹' . $application->emi->advance_emi;
                }

                $advance_amount = $application->emi->upfront_from_customer;
                $interest_rate = $application->emi->interest_rate > 0 ? $application->emi->interest_rate : 'No Cost EMI';
                $column_text = 'Approved Amount';
                $amount = $application->approved_amount;
                if ($application->emi->interest_rate == 0) {
                    $column_text = 'Repayable Amount';
                    $accountingController = new AccountingController();
                    $schedule = $accountingController->viewloanschedule($application->id, 1);
                    if (isset($schedule) && $schedule != '') {
                        if (isset($schedule['schedule'][0])) {
                            $repayable = $application->emi->upfront_from_customer;
                            $principal_amount = 0;
                            $subvention = 0;
                            $total_interest = 0;
                            $is_gst = isset($application->merchant->is_gst) ? $application->merchant->is_gst : 0;
                            foreach ($schedule['schedule'] as $key => $loan_schedule) {
                                $repayable = $repayable + $loan_schedule['amount'];
                                $principal_amount = $principal_amount + $loan_schedule['principal'];
                                $subvention = $subvention + $loan_schedule['subvention'];
                                $total_interest = $total_interest + ($loan_schedule['subvention'] + $loan_schedule['interest']);
                                if ($is_gst == 0 && $subvention > 0) {
                                    $amount = ($principal_amount + $application->emi->upfront_from_customer) - $subvention;
                                } else {
                                    $amount = $principal_amount + $application->emi->upfront_from_customer;
                                }
                            }
                        }
                    }
                }
            }

            $script = MerchantCategoryScripts::where('category_id',$application->merchant->merchant_category->id)->first(['script_content']);
            $script = $this->simplyVerificationScript($script->script_content, ['column_text' => $column_text,'name' => $name, 'dob' => $dob, 'application' => $application, 'approved_amount' => $application->approved_amount, 'amount' => $amount, 'interest_rate' => $interest_rate, 'advance_amount' => $advance_amount, 'advance_emi' => $advance_emi]);
            /*switch ($application->merchant->merchant_category->id) {
                case 25:
                $script = MerchantCategoryScripts::where('script_id',$application->merchant->merchant_category->id)->get(['script_content']);
//                    $script = "Dear <b>" . $name . ",</b><br/>Congrats on being approved by Credit Fair!<br/>This is a verification call for the loan that you’ve applied for from " . $application->merchant->merchant_name . "<br/><br/>Please confirm your Date of Birth<br/><br/>Following are the loan details  :<br/><br/><table class='table'><tr><th>Date of Birth</th><th>".$column_text."</th><th>Installment Amount</th><th>Tenure</th><th>Advance</th><th>Advance Amount</th><th>Processing Fee</th><th>Interest Rate</th></tr><tr><td>" . $dob . "</td><td>" . $amount . "</td><td>" . $application->emi->emi . "</td><td>" . $application->emi->tenure . "</td><td>" . $advance_emi . "</td><td>" . $advance_amount . "</td><td>" . $application->emi->processing_fee . "</td><td>" . $interest_rate . "</td></tr></table><br/>Your EMI of " . $application->emi->emi . " will be deducted every month on " . date('d M, Y', strtotime($application->emi->emi_date)) . ". Regardless of the result of your treatment, EMI will have to be paid. Responsibility of Treatment related issues is with " . $application->merchant->merchant_name . " & if you have any issues relating to Finance, you can contact us. Please confirm the Treatment you are getting done from " . $application->merchant->merchant_name . "<br/><br/>Please give as an alternate number in case we aren’t able to reach you.  Also please provide contact details of 2 of your References (Family/Friends/Colleagues).<br/><br/>Please make sure that you verify the Visitor's ID Card before making EMI Payment in Cash. Please insist on receiving a Payment Receipt after paying the EMI.<br/><br/>Thank you!";
                    break;
                case 6:
                case 7:
                case 28:
                case 22:
                case 14:
                case 24:
                case 23:
                $script = MerchantCategoryScripts::where('script_id',$application->merchant->merchant_category->id)->get(['script_content']);

//                    $script = "Dear <b>" . $name . ",</b><br/>Congrats on being approved by Credit Fair!<br/>This is a verification call for the loan that you’ve applied for from " . $application->merchant->merchant_name . "<br/><br/>Please confirm your Date of Birth<br/><br/>Following are the loan details  :<br/><br/><table class='table'><tr><th>Date of Birth</th><th>".$column_text."</th><th>Installment Amount</th><th>Tenure</th><th>Advance</th><th>Advance Amount</th><th>Processing Fee</th><th>Interest Rate</th></tr><tr><td>" . $dob . "</td><td>" . $amount . "</td><td>" . $application->emi->emi . "</td><td>" . $application->emi->tenure . "</td><td>" . $advance_emi . "</td><td>" . $advance_amount . "</td><td>" . $application->emi->processing_fee . "</td><td>" . $interest_rate . "</td></tr></table><br/>Responsibility of Product related issues is with " . $application->merchant->merchant_name . " & if you have any issues relating to Finance, you can contact us. Please confirm the Product you are purchasing from " . $application->merchant->merchant_name . "<br/><br/>Please give as an alternate number in case we aren’t able to reach you.<br/><br/>Also please provide contact details of 2 of your References (Family/Friends/Colleagues).<br/><br/>Please make sure that you verify the Visitor's ID Card before making EMI Payment in Cash. Please insist on receiving a Payment Receipt after paying the EMI.<br/><br/>Thank you!";
                    break;
                case 20:
                case 16:
                case 19:
                case 21:
                $script = MerchantCategoryScripts::where('script_id',$application->merchant->merchant_category->id)->get(['script_content']);

//                    $script = "Dear <b>" . $name . ",</b><br/>Congrats on being approved by Credit Fair!<br/>This is a verification call for the loan that you’ve applied for from " . $application->merchant->merchant_name . "<br/><br/>Please confirm your Date of Birth<br/><br/>Following are the loan details  :<br/><br/><table class='table'><tr><th>Date of Birth</th><th>".$column_text."</th><th>Installment Amount</th><th>Tenure</th><th>Advance</th><th>Advance Amount</th><th>Processing Fee</th><th>Interest Rate</th></tr><tr><td>" . $dob . "</td><td>" . $amount . "</td><td>" . $application->emi->emi . "</td><td>" . $application->emi->tenure . "</td><td>" . $advance_emi . "</td><td>" . $advance_amount . "</td><td>" . $application->emi->processing_fee . "</td><td>" . $interest_rate . "</td></tr></table><br/>Responsibility of Service related issues is with " . $application->merchant->merchant_name . " & if you have any issues relating to Finance, you can contact us. Please confirm the Treatment you are getting done from " . $application->merchant->merchant_name . "<br/>Please give as an alternate number in case we aren’t able to reach you.  Also please provide contact details of 2 of your References (Family/Friends/Colleagues).<br/><br/>Please make sure that you verify the Visitor's ID Card before making EMI Payment in Cash. Please insist on receiving a Payment Receipt after paying the EMI.<br/><br/>Thank you!";
                    break;
                case 3:
                case 26:
                $script = MerchantCategoryScripts::where('script_id',$application->merchant->merchant_category->id)->get(['script_content']);

//                    $script = "Dear <b>" . $name . ",</b><br/>Congrats on being approved by Credit Fair!<br/>This is a verification call for the Personal loan that you’ve applied for<br/><br/>Please confirm your Date of Birth<br/><br/>Following are the loan details  :<br/><br/><table class='table'><tr><th>Date of Birth</th><th>".$column_text."</th><th>Installment Amount</th><th>Tenure</th><th>Advance</th><th>Advance Amount</th><th>Processing Fee</th><th>Interest Rate</th></tr><tr><td>" . $dob . "</td><td>" . $amount . "</td><td>" . $application->emi->emi . "</td><td>" . $application->emi->tenure . "</td><td>" . $advance_emi . "</td><td>" . $advance_amount . "</td><td>" . $application->emi->processing_fee . "</td><td>" . $interest_rate . "</td></tr></table><br/>If you have any issues relating to Finance, you can contact us.  Please confirm the reason for taking this loan.<br/>Please give as an alternate number in case we aren’t able to reach you.  Also please provide contact details of 2 of your References (Family/Friends/Colleagues).<br/><br/>Please make sure that you verify the Visitor's ID Card before making EMI Payment in Cash. Please insist on receiving a Payment Receipt after paying the EMI.<br/><br/>Thank you!";
                    break;
                case 4:
                $script = MerchantCategoryScripts::where('script_id',$application->merchant->merchant_category->id)->get(['script_content']);
//                    $script = "Dear <b>" . $name . ",</b><br/>Congrats on being approved by Credit Fair!<br/>This is a verification call for the loan that you’ve applied for from " . $application->merchant->merchant_name . "<br/><br/>Please confirm your Date of Birth<br/><br/>Following are the loan details  :<br/><br/><table class='table'><tr><th>Date of Birth</th><th>".$column_text."</th><th>Installment Amount</th><th>Tenure</th><th>Advance</th><th>Advance Amount</th><th>Processing Fee</th><th>Interest Rate</th></tr><tr><td>" . $dob . "</td><td>" . $amount . "</td><td>" . $application->emi->emi . "</td><td>" . $application->emi->tenure . "</td><td>" . $advance_emi . "</td><td>" . $advance_amount . "</td><td>" . $application->emi->processing_fee . "</td><td>" . $interest_rate . "</td></tr></table><br/>Responsibility of Service related issues during your course is with " . $application->merchant->merchant_name . " & if you have any issues relating to Finance, you can contact us. Please confirm the Course you have applied for from " . $application->merchant->merchant_name . "<br/>Please give as an alternate number in case we aren’t able to reach you.  Also please provide contact details of 2 of your References (Family/Friends/Colleagues).<br/><br/>Please make sure that you verify the Visitor's ID Card before making EMI Payment in Cash. Please insist on receiving a Payment Receipt after paying the EMI.<br/><br/>Thank you!";
                    break;
            }*/
        }

        return (isset($script)) ? response()->json(['status' => 'OK', 'data' => '<b>Verification Call Script</b> <br/><br/>' . $script], 200) : response()->json(['status' => 'FAIL'], 200);
    }

    public function simplyVerificationScript($script_content, $applicationData){
        $script_content = str_replace('  ',' ',$script_content);
        $lists = ['Merchant',
            'Customer Name',
            'Date of Birth',
            'Approved Amount',
            'Repayable Amount',
            'Installment Amount',
            'Insurance Premium Amount',
            'Tenure',
            'EMI Date',
            'Advance',
            'Advance Amount',
            'Processing Fee',
            'Interest Rate'];

        $prefix = "@table";
        $index = strpos($script_content, $prefix) + strlen($prefix);
        $result = substr($script_content, $index);
        $tableBody = substr($result, 0, strpos($result, $prefix));

        $r1 = Strip_tags($tableBody);
        $dataItems =  array_values(array_filter(explode('@',$r1)));

        $table = "<table class='table'>";
        $td = '';
        $th = '';
        foreach ($dataItems as $index => $item){
            $_item_ = trim(str_replace("&nbsp;",'',str_replace("\n",'',$item)));
            $_item = trim(preg_replace('/\s+/', '',str_replace("&nbsp;",'',str_replace("\n",'',$item))));
            if($applicationData['application']->emi->interest_rate == 0 && $_item == 'ApprovedAmount'){
                continue;
            }else if($applicationData['application']->emi->interest_rate && $_item == 'RepayableAmount'){
                continue;
            }
            $th .= '<th>'.$_item_.'</th>';
            $td .= '<td>'.$this->getDataValues($_item, $applicationData).'</td>';
            $dataItems[$index] = $_item;
        }

        $table .= '<thead>';
        $table .= $th;
        $table .= '</thead><tbody>';
        $table .= $td;
        $table .= "</tbody></table>";

        $script_content = preg_replace('#@table[^>]*>.*?@table#si', $table, $script_content);


        foreach ($lists as $item){
            $_item = trim(preg_replace('/\s+/', '',str_replace("&nbsp;",'',str_replace("\n",'',$item))));
            $value = $this->getDataValues($_item, $applicationData);
            $script_content = str_replace('@'.$item, $value, $script_content);
        }

        return $script_content;
    }

    public function getDataValues($item, $applicationData){
        $application = $applicationData['application'];
        $value = $item;
        switch($item){
            case 'Merchant':
                $value = $application->merchant->merchant_name;
                break;
            case 'CustomerName':
                $value = $applicationData['name'];
                break;
            case 'DateofBirth':
                $value = $applicationData['dob'];
                break;
            case 'ApprovedAmount':
                $value = $applicationData['approved_amount'];
                break;
            case 'RepayableAmount':
                $value = $applicationData['amount'];
                break;
            case 'InstallmentAmount':
                $value = $application->emi->emi;
                break;
            case 'Tenure':
                $value = $application->emi->tenure;
                break;
            case 'EMIDate':
                $value = $application->emi->emi_date;
                break;
            case 'Advance':
                $value = $applicationData['advance_emi'];
                break;
            case 'AdvanceAmount':
                $value = $applicationData['advance_amount'];
                break;
            case 'InsurancePremiumAmount':
                $value = $application->proFormaInvoice ? $application->proFormaInvoice->insurance_premium_amount : 0;
                break;
            case 'ProcessingFee':
                $value = $application->emi->processing_fee;
                break;
            case 'InterestRate':
                $value = $applicationData['interest_rate'];
                break;
        }

        return $value;
    }

    public function saveNegativeProfile($id)
    {
        if (Input::has('profile_id') && Input::get('profile_id') > 0) {
            $elementID = ConsumerApplicationElement::where('application_id', $id)->first(['id']);
            if (isset($elementID->id)) {
                ConsumerApplicationElement::where('application_id', $id)->update(['negative_profile' => Input::get('profile_id')]);
            } else {
                ConsumerApplicationElement::insert(['application_id' => $id, 'negative_profile' => Input::get('profile_id')]);
            }
            $_checklist = Checklist::where('application_id', $id)->first(['id']);

            if (isset($_checklist->id)) {
                $checklist = Checklist::find($_checklist->id);
            } else {
                $checklist = new Checklist();
                $checklist->application_id = $id;
            }

            $checklist->negative_profession = Input::get('profile_id');

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

    public function getCompanyLists(Request $request)
    {
        $company = $request->has('company') && $request->get('company') ? $request->get('company') : $request->get('state');

        $companies = Company::where('company', 'LIKE', '%' . $company . '%')->limit(10)->get();
        $options = '<ul>';
        foreach ($companies as $company) {
            $options .= '<li class="select_company_list" value=' . $company->id . '>' . $company->company . '</li>';
        }
        $options .= '</ul>';

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

    public function getRealNameOfFile($file)
    {
        if ($file instanceof UploadedFile) {
            return $file->getClientOriginalName();
        }
        return 'Other';
    }

    public function checkImageQuality($file_type_name, $file, $getClientOriginalExtension = false)
    {
//        $isBlurry = false;
        $score = 0;
        $path = storage_path('images');
        if(!$getClientOriginalExtension) {
            $name = $file_type_name . '.' . $file->getClientOriginalExtension();
            $file->move($path, $name);
        }else{
            $name = $file_type_name.$getClientOriginalExtension;
            file_put_contents($path.'/'.$name, $file);
        }
        $file = file_get_contents($path . '/' . $name);

        ///usr/local/bin/python
        exec('/usr/bin/python ' . public_path() . '/images.py --images ' . storage_path() . '/images 2>&1', $output, $return);


        if (isset($output[0]) && $output[0] > 0) {
            $score = $output[0];
        }
        unlink($path . '/' . $name);
        return ['imageScore' => $score, 'file' => $file];
    }

    public function checkPincode(Request $request){
        if($request->has('pincode')){
            $list = ApprovedPincodeLists::where('pin_codes', $request->get('pincode'))->first(['id']);
            if(isset($list->id)){
                return response()->json(['status' => 'OK']);
            }
        }

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

    private function createZipFromBankStatements(array $files, string $zipNamePrefix): ?\Illuminate\Http\UploadedFile
    {
        if (empty($files)) {
            return null;
        }

        $zip = new \ZipArchive();
        $zipFilePath = tempnam(sys_get_temp_dir(), 'bank_statements_') . '.zip';

        if ($zip->open($zipFilePath, \ZipArchive::CREATE | \ZipArchive::OVERWRITE) !== TRUE) {
            error_log("Failed to create zip archive at: " . $zipFilePath);
            return null;
        }

        foreach ($files as $file) {
            if (!$file instanceof \Illuminate\Http\UploadedFile || !$file->isValid()) {
                continue;
            }

            $extension = strtolower($file->getClientOriginalExtension());
            
            if ($extension === 'zip') {
                $existingZip = new \ZipArchive();
                if ($existingZip->open($file->getPathname()) === TRUE) {
                    for ($i = 0; $i < $existingZip->numFiles; $i++) {
                        $filename = $existingZip->getNameIndex($i);
                        // To avoid nested zips, only extract PDFs from existing archives
                        if (preg_match('/\.pdf$/i', $filename)) {
                            $zip->addFromString($filename, $existingZip->getFromIndex($i));
                        }
                    }
                    $existingZip->close();
                }
            } else if ($extension === 'pdf') {
                $zip->addFile($file->getPathname(), $file->getClientOriginalName());
            }
        }

        if ($zip->numFiles > 0 && $zip->close()) {
            $finalZipName = $zipNamePrefix . '.zip';
            return new \Illuminate\Http\UploadedFile(
                $zipFilePath,
                $finalZipName,
                'application/zip',
                UPLOAD_ERR_OK,
                true // Mark as test file since it was created on the server
            );
        } else {
            $zip->close(); // Close it even if empty
            @unlink($zipFilePath); // Clean up empty/failed zip file
            error_log("Zip creation failed or was empty for prefix: " . $zipNamePrefix);
            return null;
        }
    }

    private function processAndSubmitBankStatements($id, $type, array $bankStatementCollection, $app)
    {
        $s3 = Storage::disk('s3');

        // Initiate latest bank statement check once before processing all statements.
        if ($type == 'consumer' && $app && $app->merchant_id != 6543) {
            $this->initiateForLatestBankStatement($id, true);
        }

        foreach ($bankStatementCollection as $applicantType => $statementData) {
            $files = $statementData['files'];
            $passwords = $statementData['passwords'] ?? [];

            // NEW: Logic diverges based on the number of files.
            if (count($files) > 1) {
                // --- SCENARIO 1: MULTIPLE FILES (Zipping required) ---

                $zipNamePrefix = ($applicantType === 'co_applicant') ? 'co_applicant_bank_statements' : 'applicant_bank_statements';
                $finalFile = $this->createZipFromBankStatements($files, $zipNamePrefix);
                if (!$finalFile) {
                    error_log("Failed to create zip for applicant type: {$applicantType}, ID: {$id}");
                    continue;
                }

                // 2. Upload the final zip to S3
                $file_type = ($applicantType === 'co_applicant') ? 'co_applicant_bank_statement' : 'bank_statement';
                $file_path_base = '';
                if ($type == 'merchant') {
                    $file_path_base = '/merchant';
                }
                if ($type == 'lead' || $type == 'lead_type') {
                    $file_path_base = '/lead';
                }

                if ($type == 'merchant_location') {
                    $file_path_base = '/merchant_location';
                }
                $file_path = "{$file_path_base}/{$id}/{$file_type}.zip";

                // 3. Prepare data for DB and Pirimid
                $dbData = [];
                $dbData['file_type'] = $file_type;
                $dbData['id'] = $id;
                $dbData['applicant_type'] = ($applicantType === 'co_applicant') ? 2 : 1;
                $firstMeta = $statementData['meta'][0] ?? [];
                $dbData['bank_name'] = $firstMeta['bank_name'] ?? '';
                $dbData['accounttype'] = $firstMeta['accounttype'] ?? '';
                $dbData['ismerchant'] = in_array($type, ['merchant', 'merchant_location', 'lead']) ? 1 : 0;
                $dbData['operation_type'] = $type;

                if (!empty($passwords)) {
                    if (is_array($passwords)) {
                        $dbData['password'] = implode(',', array_map('trim', $passwords));
                    } else {
                        $dbData['password'] = trim($passwords);
                    }
                } else {
                    $dbData['password'] = '';
                }

                try {
                    $pirimidData = [];
                    $pirimidData['id'] = $id;
                    $pirimidData['uploaded_file'] = $finalFile;
                    $pirimidData['passwords_list'] = $passwords;
                    $pirimidData['applicant_type'] = $dbData['applicant_type'];
                    $pirimidData['file_type'] = $file_type;
                    $pirimidData['employmentType'] = $statementData['employmentType'] ?? '';

                    $bankStatement = (new Pirimid(new Request($pirimidData)))->uploadBankStatement();

                    if (!isset($bankStatement->trackingId) && !isset($bankStatement->status) && $bankStatement->status != 'pending') {
                        $dbData['finbit_analysis_date'] = Carbon::now()->toDateTimeString();
                    }

                    $this->getUploadedFileNameMultiple($s3, $file_path, $dbData);

                } catch (\Exception $e) {
                    error_log("Pirimid API call failed for MULTI-FILE applicant type: {$applicantType}, ID: {$id}. Error: " . $e->getMessage());
                }

            } else {
                $finalFile = $files[0];

                try {
                    $file_type = ($applicantType === 'co_applicant') ? 'co_applicant_bank_statement' : 'bank_statement';
                    $applicant_type_id = ($applicantType === 'co_applicant') ? 2 : 1;

                    $pirimidData = [];
                    $pirimidData['id'] = $id;
                    $pirimidData['uploaded_file'] = $finalFile;
                    $pirimidData['passwords_list'] = $passwords;
                    $pirimidData['applicant_type'] = $applicant_type_id;
                    $pirimidData['file_type'] = $file_type;
                    $pirimidData['employmentType'] = $statementData['employmentType'] ?? '';

                    $bankStatement = (new Pirimid(new Request($pirimidData)))->uploadBankStatement();

                    // For a single file, we run a direct query instead of setting $dbData.
                    if (!isset($bankStatement->trackingId) && !isset($bankStatement->status) && $bankStatement->status != 'pending') {
                        ConsumerApplicationFiles::where('consumer_application_id', $id)
                            ->where('file_type', $file_type)
                            ->orderBy('created_at', 'desc')
                            ->limit(1)
                            ->update(['finbit_analysis_date' => Carbon::now()]);
                    }
                } catch (\Exception $e) {
                    error_log("Pirimid API call failed for SINGLE-FILE applicant type: {$applicantType}, ID: {$id}. Error: " . $e->getMessage());
                }
            }
        }
    }

    public function uploadConsumerDocuments(Request $request, $id, $type = 'consumer')
    {
        $blur = false;
        $score = 0;
        $s3 = Storage::disk('s3');
        $unprocessed_documents = [];
        $status = 'OK';
        $advanceReceiptUploaded = false;

        $bankStatementCollection = [];
        $app = null;
        if ($type == 'consumer') {
            $app = ConsumerApplication::where('id', $id)->first(['merchant_id', 'employee_status']);
        }

        if($type == 'lead_type'){
            $type1 = 'lead_type';
            $type = 'lead';
        }

        if (isset($request->fileNamePDF)) {
            $docsName = 0;
            $multiple_file_type = 0;
            foreach ($request->fileNamePDF as $_key => $fileArray) {
                $file_type = !(strpos($_key, 'other') !== false) && $_key ? $_key : $request->get('fileName')[$docsName];
                $file_type_original = $file_type;
                $file_type =  str_replace('-', ' ', preg_replace('/[^A-Za-z0-9_.\-]/', '', str_replace(' ', '-', $file_type)));

                if(strpos($_key, 'bank_statement') !== false && $_key !== 'co_applicant_bank_statement'){
                    if(substr($file_type,-2,-1) == "_"){
                        $file_type = $file_type;
                    }else{
                        $file_type = str_replace(substr($file_type,-1), "_".substr($file_type,-1), $file_type);
                        //$file_type = str_replace('_', ' ', $file_type);
                    }
                }
                if(strpos($_key, 'aadhar_card') !== false ){
                    $s3 = Storage::disk('s3_temp');
                    $filePaths3 = 'https://' . _env('AWS_TEMP_BUCKET') . _env('AWS_ORIGIN') . '/';
                }else{
                    $s3 = Storage::disk('s3');
                    $filePaths3 = 'https://'._env('AWS_BUCKET')._env('AWS_ORIGIN') . '/';
                }

                foreach ($fileArray as $__key => $file) {
                    if (strpos($_key, 'bank_statement') !== false) {
                        $applicantType = (strpos($_key, 'co_applicant') !== false) ? 'co_applicant' : 'applicant';

                        // Collect the file object
                        $bankStatementCollection[$applicantType]['files'][] = $file;

                        // Collect the password, ensuring no duplicates
                        $password = $request->get('password')[$docsName] ?? '';
                        if (!empty($password)) {
                            if (!isset($bankStatementCollection[$applicantType]['passwords'])) {
                                $bankStatementCollection[$applicantType]['passwords'] = [];
                            }
                            if (!in_array($password, $bankStatementCollection[$applicantType]['passwords'])) {
                                $bankStatementCollection[$applicantType]['passwords'][] = $password;
                            }
                        }
                        
                        if (!isset($bankStatementCollection[$applicantType]['employmentType'])) {
                            $bankStatementCollection[$applicantType]['employmentType'] = $app->employee_status ?? '';
                        }
                    }
                    $file_path = '';
                    if ($type == 'merchant') {
                        $file_path = '/merchant';
                    }
                    if ($type == 'lead' || $type == 'lead_type') {
                        $file_path = '/lead';
                    }

                    if ($type == 'merchant_location') {
                        $file_path = '/merchant_location';
                    }

                    $_extension = $file->getClientOriginalExtension();
                    $file_path .= '/' . $id . '/' . $file_type . '.' . $_extension;
                    $file_type_name = $file_type;
                    if ($__key >= 1) {
                        $file_type_name .= ' ' . $__key;
                    }

                    //HomeVille Agreement API Calling
                    $created_by = (Auth::check()) ? Auth::user()->id : null;
                    if(($file_type == "pro_forma_invoice" && $created_by != null && $created_by != 107) || ($file_type == "proforma" && $created_by == null)){
                        $consumerApplication = ConsumerApplication::where('id', $id)->first(['lender_id']);
                        if (isset($consumerApplication->lender_id) && $consumerApplication->lender_id == Singularity::$lender_id) {
                            $this->homevill_callback = (new HomevilleController(new Request(['id' => $id])))->generateDocument();
                            $homeville_callback = $this->homevill_callback->getData();
                            if(isset($errorHomeVille->message) && $homeville_callback->message != 'Document Generated Successfully') {
                                if (!isset($this->homevill_callback->documentUrl)) {
                                    return false;
                                }
                            }else{
                                $this->homevill_callback = false;
                            }
                        }
                    }
                    //End

                    $score = 0;
                    if ($file && $file != '') {

                        $s3_object_id = $s3->put($file_path, $file);

                        $data['file_type'] = $file_type_name;
                        $data['id'] = $id;
                        $data['image_score'] = isset($score) ? $score : 0;
                        $data['file_type_original'] = $file_type_original;
                        $data['bank_name'] = (isset($request->get('bankname')[$docsName])) ? $request->get('bankname')[$docsName] : '';
                        $data['password'] = (isset($request->get('password')[$docsName])) ? $request->get('password')[$docsName] : '';
                        $data['accounttype'] = (isset($request->get('accounttype')[$docsName])) ? $request->get('accounttype')[$docsName] : '';
                        $data['statementtype'] = (isset($request->get('statementtype')[$docsName])) ? $request->get('statementtype')[$docsName] : '';
                        $data['statemenfilettype'] = (isset($request->get('statemenfilettype')[$docsName])) ? $request->get('statemenfilettype')[$docsName] : '';

                        $data['customerID'] = (isset($request->get('customerID')[$docsName])) ? $request->get('customerID')[$docsName] : '';
                        $data['provider'] = (isset($request->get('provider')[$docsName])) ? $request->get('provider')[$docsName] : '';
                        $data['district'] = (isset($request->get('discom_district')[$docsName])) ? $request->get('discom_district')[$docsName] : '';
                        $data['mobile_number'] = (isset($request->get('discom_mobile')[$docsName])) ? $request->get('discom_mobile')[$docsName] : '';
                        $data['png_provider'] = (isset($request->get('png_provider')[$docsName])) ? $request->get('png_provider')[$docsName] : '';
                        $data['BPNumber'] = (isset($request->get('BPNumber')[$docsName])) ? $request->get('BPNumber')[$docsName] : '';

                        if(strpos($file_type,'equifax_report') !== false){
                            if($file_type == 'equifax_report'){
                                $data['bureau_report_type'] = $file_type == 'equifax_report' ? ((isset($request->get('bureau_reports')[$multiple_file_type])) ? $request->get('bureau_reports')[$multiple_file_type] : '') : '';
                                $data['bureau_report_score'] = $file_type == 'equifax_report' ? ((isset($request->get('bureau_reports_score')[$multiple_file_type])) ? $request->get('bureau_reports_score')[$multiple_file_type] : '') : '';
                            }
                            if($file_type == 'co_applicant_equifax_report'){
                                if($request->get('bureau_reports')[$multiple_file_type] == 'Equifax v2.0' || $request->get('bureau_reports')[$multiple_file_type] == 'CIBIL CreditVision'){
                                    $data['bureau_report_type'] = 'Co-Applicant '.$request->get('bureau_reports')[$multiple_file_type];
                                }
                                $data['bureau_report_score'] = $file_type == 'co_applicant_equifax_report' ? ((isset($request->get('bureau_reports_score')[$multiple_file_type])) ? $request->get('bureau_reports_score')[$multiple_file_type] : '') : '';
                            }
                        }else{
                            $data['bureau_report_type'] = '';
                            $data['bureau_report_score'] = '';
                        }

                        // if(strpos($_key, 'co_applicant') !== false) {
                        //     $data['applicant_type'] = 2;
                        // } else {
                        //     $data['applicant_type'] = 1;
                        // }

                        $documentInfo = \App\UserDocument::where('file_type', $_key)->value('role'); // find the role of uploded document
                        $applicantType = 1; // Default to Applicant (type 1)
                        if ($documentInfo) {
                            switch ($documentInfo) {
                                case 'co_applicant':
                                    $applicantType = 2;
                                    break;
                                case 'merchant':
                                    $applicantType = 3;
                                    break;
                                default:
                                    $applicantType = 1; // applicant or anything else
                                    break;
                            }
                        }
                        $data['applicant_type'] = $applicantType;
                        $data['uploaded_file'] = $file;
                        $data['isMerchantPipe'] = $type;
                        if (in_array($data['file_type'], ['net_metering_agreement', 'commissioning_certificate', 'work_completion_report', 'sync_report'])) {
                            $this->initiateAAMonitoringRequest($id, 'document_upload');
                        }
                        if ($s3) {
                            if ($type == 'merchant' || $type == 'merchant_location' || $type == 'lead') {
                                if(isset($type1)){
                                    $data['ismerchant'] = 0;
                                    $data['operation_type'] = $type;
                                }else{
                                    $data['ismerchant'] = 1;
                                    $data['operation_type'] = $type;
                                }
                            } else {
                                $data['ismerchant'] = 0;
                            }

                            $this->getUploadedFileNameMultiple($s3, $file_path, $data);

                            if ($file_type == 'advance_amount_receipt') {
                                $advanceReceiptUploaded = true;
                            }

                            if(strpos($data['file_type'], 'aadhar_card') !== false) {
                                $this->maskAadhaarCard($filePaths3.$s3_object_id, $data['file_type'], $id);
                            }
                        }
                    }

                    $multiple_file_type++;
                }
                $docsName++;
            }

        }

        if (!empty($bankStatementCollection)) {
            $this->processAndSubmitBankStatements($id, $type, $bankStatementCollection, $app);
        }

        if($type == 'consumer') {
            $this->isScheduleVerificationCall($id);
            if ($advanceReceiptUploaded) {
                $this->reviseDocsOnAdvanceReceiptUpload($id);
            }
        }

        return ['score' => $score, 'file_type' => isset($file_type_name) ? $file_type_name : '', 'status' => $status, 'documents' => $unprocessed_documents];
    }
    public function maskAadhaarCard($s3_object_id, $document_type, $id){
        (new Slack(new Request(['title' => 'Mask Aadhaar Card Function', 'fields' => ['s3_object_id' => $s3_object_id, 'document_type' => $document_type, 'id' => $id], 'group' => Slack::$STAGE_TESTING])))->send();
        $request = new Request(['file_type' => $s3_object_id, 'link' => true, 'type' => strpos($document_type, 'aadhar_card') !== false ? 'aadhaar_card' : $document_type, 'id' => $id, 'auto_mask' => true]);
        (new OCRRecognition($request))->get();
    }

    public function addAvanseDocuments($id, $name, $file_path, $consumer_application_file_id, $file){

        $documents = DB::connection('avanse')->table('BMTDocumentTypes')->where('DocTypeCode', $name)->first(['DocTypeCode']);
        if (isset($documents->DocTypeCode)) {

            $avanseProcesses = new AvanseProcesses(new Request(['files' => [[
                'file_type' => $name,
                'file_path' => $file_path,
                'file' => $file,
                'id' => $id,
                'applicant_type' => 1,
                'consumer_application_file_id' => $consumer_application_file_id
            ]],
            'id' => $id,
            'consumer_application_file_id' => $consumer_application_file_id]));

            $avanseProcesses->addDocuments();
        }
        return false;
    }

    public function isScheduleVerificationCall($id)
    {
        $consumer_applications = ConsumerApplication::with('checkmandate', 'offer.disbursementOffer', 'documents', 'logs', 'digital_sign', 'merchant', 'merchant.anchorMerchant', 'merchant.merchant_category', 'category', 'emi', 'creditReport', 'application_element.merchant_center', 'advisor', 'comments.user', 'bank_details')->where('id', $id)->first();
        if ($consumer_applications->state == 'approved') {
            $this->pendingDoc($consumer_applications, array());
        }
    }

    public function uploadMerchantFiles($id, $file_type, $s3_path, $request, $docsName)
    {
        $consumer_application_file = new MerchantFiles();
        $consumer_application_file->merchant_id = $id;
        $consumer_application_file->file_type = $file_type;
        $consumer_application_file->bank_name = (isset($request->get('bankname')[$docsName])) ? $request->get('bankname')[$docsName] : '';
        $consumer_application_file->password = (isset($request->get('password')[$docsName])) ? $request->get('password')[$docsName] : '';
        $consumer_application_file->file_path = $s3_path;
        $consumer_application_file->save();
    }

    public function uploadConsumerFiles($id, $file_type, $s3_path, $request, $docsName = '')
    {
        if($id) {
            $consumer_application_file = new ConsumerApplicationFiles();
            $consumer_application_file->consumer_application_id = $id;
            $consumer_application_file->file_type = $file_type;
            $consumer_application_file->bank_name = (isset($request->get('bankname')[$docsName])) ? $request->get('bankname')[$docsName] : '';
            $consumer_application_file->password = (isset($request->get('password')[$docsName])) ? $request->get('password')[$docsName] : '';
            $consumer_application_file->file_path = $s3_path;
            $consumer_application_file->applicant_type = $request->get('appType') ?? null;
            $consumer_application_file->save();
        }
    }

    public function getUploadedFileName($s3, $file_path)
    {
        $list = $s3->listContents($file_path);
        if ($list) {
            $data = [];
            foreach ($list as $key => $row) {
                $data[$key] = $row['timestamp'];
            }
            array_multisort($data, SORT_DESC, $list);
            return (count($list) > 0) ? (isset($list[0]['path']) ? $list[0]['path'] : '') : '';
        }
        return '';
    }

    public function uploadDocumentSingle(Request $request)
    {
        if ($request->hasFile('file') && $request->has('id') && $request->has('file_type')) {
            $id = $request->get('id');
            $file = $request->file('file');
            $file_type = explode('.', $request->get('file_type'))[0];

            // Clean file type string
            $file_type = str_replace('-', ' ', preg_replace('/[^A-Za-z0-9_.\-]/', '', str_replace(' ', '-', $file_type)));

            $extension = $file->getClientOriginalExtension();
            $file_path = $id . '/' . $file_type . '_' . (time() + rand(1, 100)) . '.' . $extension;

            $s3 = Storage::disk('s3');
            $s3->put($file_path, fopen($file->getRealPath(), 'r'));

            $consumer_application_file = new ConsumerApplicationFiles();
            $consumer_application_file->consumer_application_id = $id;
            $consumer_application_file->file_type = $file_type;
            $consumer_application_file->file_path = $file_path;
            if ($request->has('applicant_type')) {
                $consumer_application_file->applicant_type = $request->get('applicant_type') == 'Applicant' ? 1 : 2;
            }
            $consumer_application_file->created_by = (Auth::check()) ? Auth::user()->id : null;
            $consumer_application_file->save();

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

        return response()->json(['status' => 'error', 'message' => 'Missing required fields'], 400);
    }

    public function getGSTPanDetails(Request $request){
        $panGst = (new KarzaAPI())->getGSTByPan($request->get('application_id'), $request->get('pan'), $request->get('type'), $request->get('user_id'));
        if($panGst){
            $status = ((isset($panGst['statusCode']) && $panGst['statusCode'] == 101) || isset($panGst->statusCode) && $panGst->statusCode == 101) ? 'OK': 'FAIL';
            $message = ((isset($panGst['statusCode']) && $panGst['statusCode'] == 103) || isset($panGst->statusCode) && $panGst->statusCode == 103) ? 'No Data Found' : '';
            return \response()->json(['status' => $status, 'message' => isset($panGst['error']) ? $panGst['error'] : ($message ? $message : 'Details are fetched')]);
        }

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


    public function getUploadedFileNameMultiple($s3, $file_path, $data = array(), $masked = false)
    {
        $id = isset($data['id']) ? ($data['id']) : 0;
        $operation_type = isset($data['operation_type']) ? $data['operation_type'] : '';
        $location_id = isset($data['location_id']) ? ($data['location_id']) : 0;
        $file_type = isset($data['file_type']) ? ($data['file_type']) : "";

        $file_type =  str_replace('-', ' ', preg_replace('/[^A-Za-z0-9_.\-]/', '', str_replace(' ', '-', $file_type)));
        $show_to_merchant = isset($data['show_to_merchant']) ? ($data['show_to_merchant']) : 0;
        $bank_name = isset($data['bank_name']) ? ($data['bank_name']) : "";
        $file_type_original = isset($data['file_type_original']) ? ($data['file_type_original']) : "";
        $password = isset($data['password']) ? ($data['password']) : "";
        $accounttype = isset($data['accounttype']) ? ($data['accounttype']) : "";
        $statementtype = isset($data['statementtype']) ? ($data['statementtype']) : "";
        $statemenfilettype = isset($data['statemenfilettype']) ? ($data['statemenfilettype']) : "";
        $customerID = isset($data['customerID']) ? ($data['customerID']) : "";
        $provider = isset($data['provider']) ? ($data['provider']) : "";
        $BPNumber = isset($data['BPNumber']) ? ($data['BPNumber']) : "";
        $bureau_report_type = isset($data['bureau_report_type']) ? ($data['bureau_report_type']) : "";
        $bureau_report_score = isset($data['bureau_report_score']) ? ($data['bureau_report_score']) : "";
        $png_provider = isset($data['png_provider']) ? ($data['png_provider']) : "";
        $applicant_type = isset($data['applicant_type']) ? ($data['applicant_type']) : 1;
        $finbit_analysis_date = isset($data['finbit_analysis_date']) ? ($data['finbit_analysis_date']) : null;
        $m_generated = isset($data['m_generated']) ? ($data['m_generated']) : 0;
        $discom_district = isset($data['district']) ? ($data['district']) : 0;
        $discom_mobile = isset($data['mobile_number']) ? ($data['mobile_number']) : 0;
        $doc_ref_id = isset($data['docRefId']) ? ($data['docRefId']) : null;

        $uploaded_file = isset($data['uploaded_file']) ? ($data['uploaded_file']) : 0;
        $created_by = (Auth::check()) ? Auth::user()->id : null;

        if($png_provider){
            $provider = $png_provider;
        }
        $returnFileId = 0;
        $accountUID = isset($data['accountUID']) ? ($data['accountUID']) : "";
        $setVisibility = isset($data['setVisibility']) ? ($data['setVisibility']) : 'private';
        $ismerchant = isset($data['ismerchant']) ? ($data['ismerchant']) : 0;
        $score = isset($data['image_score']) ? ($data['image_score']) : 0;
        $list = $s3->listContents($file_path);
        if (strpos($file_path, "/") == 0) {
            $file_path = substr($file_path, 1);
        }
        if ($ismerchant == 0 && $operation_type != 'lead') {
            if (isset($list[0]['path'])) {
                $existing_data = ConsumerApplicationFiles::where('consumer_application_id', $id)->where('file_path', 'LIKE', '%' . $file_path . '%')->get(['file_path']);
                $existingfiles = array();
                foreach ($existing_data as $existingfile) {
                    array_push($existingfiles, $existingfile->file_path);
                }

                if ($file_type == 'foir'){
                    ConsumerApplicationFiles::where('consumer_application_id', $id)->where('file_type','foir')->delete();
                }
                foreach ($list as $s3_files) {
                    if (!in_array($s3_files['path'], $existingfiles) && $id) {
                        if ($setVisibility == 'public') {
                            $s3->setVisibility($s3_files['path'], 'public');
                        }
                        $consumer_application_file = new ConsumerApplicationFiles();
                        $consumer_application_file->consumer_application_id = $id;
                        $consumer_application_file->file_type = $file_type;
                        $consumer_application_file->bank_name = $bank_name;
                        $consumer_application_file->password = $password;
                        $consumer_application_file->accounttype = $accounttype;
                        $consumer_application_file->statementtype = $statementtype;
                        $consumer_application_file->statemenfilettype = $statemenfilettype;
                        $consumer_application_file->customer_id = $customerID;
                        $consumer_application_file->provider = $provider;
                        $consumer_application_file->discom_district = $discom_district;
                        $consumer_application_file->discom_mobile = $discom_mobile;
                        $consumer_application_file->doc_ref_id = $doc_ref_id;

                        $consumer_application_file->finbit_analysis_date = $finbit_analysis_date;
                        $consumer_application_file->bp_number = $BPNumber;
                        $consumer_application_file->accountUID = $accountUID;
                        $consumer_application_file->file_path = $s3_files['path'];
                        if(isset($data['reference_id'])){
                            $consumer_application_file->doc_category = 'CKYC';
                        }
                        $consumer_application_file->created_by = (Auth::check()) ? Auth::user()->id : null;
                        $consumer_application_file->image_score = $score;
                        $consumer_application_file->m_generated = $m_generated;
                        $consumer_application_file->applicant_type = $applicant_type;
                        $consumer_application_file->bureau_report_type = $bureau_report_type;
                        $consumer_application_file->bureau_report_score = $bureau_report_score;
                        $consumer_application_file->is_masked = $masked == true && (strpos($file_type, 'aadhar_card') !== false || strpos($file_type, 'pan_card') !== false) ? 1 : 0;
                        $consumer_application_file->save();
                        $returnFileId = $consumer_application_file->id;

                        if (isset($data['bank_name']) && isset($data['file_type']) && $data['bank_name'] && strpos($data['file_type'], 'bank_statement') !== false) {
                            (new FinBit(new Request()))->saveFraudReportDB($id, $consumer_application_file->id);
                        }
                        if (($customerID && $data['provider']) && (strpos($data['file_type'], 'electricity_bill') !== false || strpos($data['file_type'], 'gas_bill') !== false)) {
                            $data['file_id'] = $consumer_application_file->id;
                            if ((new KarzaAPI())->utilityValidation($data)) {
                                $this->utilityValidationSucceeded = true;
                            }
                            $application_element = ConsumerApplicationElement::where('application_id', $id)->first(['id','installation_address_state']);
                            if(isset($application_element->id)){
                                (new ApiController())->triggerEbillOcr($id, $s3_files['path']);
                            }
                        }

                        if ($file_type == "advance_amount_receipt"){
                            $tag = (new WebhookController())->getCommentTag([246934, 28]); // Jayashree & mahalaxmi disbursement tags
                            $commentText = $tag." Advance amount reciept is uploaded";
                            $comment = new Comments();
                            $comment->application_id = $id;
                            $comment->user_id = Auth::user()->id ?? 107;
                            $comment->comment = $commentText;
                            $comment->show_merchant = 0;
                            $comment->show_consumer = 0;
                            $comment->save();
                            $this->reviseDocsOnAdvanceReceiptUpload($id);
                        }

                        if ($file_type == "proforma"){
                            ConsumerApplicationFiles::where('consumer_application_id', $id)->where('show_to_merchant', 1)->where('file_type','pro_forma_invoice')->update(['show_to_merchant' => 2]);
                        }
                        if ($file_type == "pro_forma_invoice"){
                            ConsumerApplicationFiles::where('consumer_application_id', $id)->where('file_type', $file_type)->where('show_to_merchant', 1)->update(['show_to_merchant' => 0]);
                            ConsumerApplicationFiles::where('id', $returnFileId)->where('file_type', $file_type)->update(['show_to_merchant' => 1]);
                        }
                        // if ($show_to_merchant > 0){
                        //     ConsumerApplicationFiles::where('id', $returnFileId)->where('file_type','pro_forma_invoice')->update(['show_to_merchant' => 1]);
                        // }

                        $consumerApplication = ConsumerApplication::where('id', $id)->first(['lender_id']);
                        if($file_type_original && $consumerApplication->lender_id == AvanseServices::$lender_id) {
                            $this->addAvanseDocuments($id, $file_type_original, $file_path, $consumer_application_file->id, $uploaded_file);
                        }

                        $hypothecation_allowed = (isset($consumerApplication->lender_id) && in_array($consumerApplication->lender_id, explode(',',_env('HYPOTHECATION_LENDERS')))) ? true : false;
                        if ($file_type == 'nach' && $consumerApplication->lender_id == Singularity::$lender_id) {
                            $this->webhook($id, ['type' => 'NACH-Webhook','status' => 'active']);
                            $sendDAWebhook = (new WebhookController())->pushDAWebhook($id, 'nach');
                            if ($sendDAWebhook) {
                                $this->webhook($id, ['type' => 'DA-Confirmation-Webhook','status' => 'pending', 'data' => $this->getMConnectPayload($id, 'DA-Confirmation-Webhook')]);
                            }
                        }
                        // Initiate Hypothecation
                        if ($hypothecation_allowed && (($file_type == "pro_forma_invoice" && (($created_by != null && $created_by != 107) || (isset($doc_ref_id) && $doc_ref_id == 'proforma by merchant'))) || ($file_type == "proforma" && $created_by == null))){
                            $apiController = new ApiController();
                            $request = new Request();
                            $request->merge(['id' => $id]);
                            $isHypothecationActive = $apiController->canHypothecated($id);
                            if ($isHypothecationActive) {
                                $loanHypothecationModel = LoanHypothecationModel::where('application_id', $id)->whereNull('deleted_at')->orderBy('created_at', 'desc')->first();
                                if (!isset($loanHypothecationModel->id)){
                                    $apiController->initiateHypothecation($request);
                                }
                            }

                            $flag = 0;
                            if(_env('DIGIO_SIGNING') == 1) {
                                $flag = (new DigioHypothecation($request))->triggerHypothecationCommunication($request->get('id'));
                            }else {
                                $hypothecation = new LoanHypothecation($request);
                                $flag = $hypothecation->triggerHypothecationCommunication($id);
                            }
                            if($flag === 1) {
                                (new Slack(new Request(['title' => 'Hypothecation Agreement Not Fetched ', 'fields' => ['application_id' => $id], 'group' => Slack::$STAGE_TESTING])))->send();
                            }else if($flag === 2){
                                (new Slack(new Request(['title' => 'Hypothecation Agreement Already Signed ', 'fields' => ['application_id' => $id], 'group' => Slack::$STAGE_TESTING])))->send();
                            }else if($flag === 3){
                                (new Slack(new Request(['title' => 'Hypothecation Agreement Email Trigger Issue ', 'fields' => ['application_id' => $id], 'group' => Slack::$STAGE_TESTING])))->send();
                            }else {
                                (new Slack(new Request(['title' => 'Hypothecation Agreement Sent ', 'fields' => ['application_id' => $id], 'group' => Slack::$STAGE_TESTING])))->send();
                            }
                        }else if(($file_type == "pro_forma_invoice" && $created_by != null && $created_by != 107) || ($file_type == "proforma" && $created_by == null)){

                        }
                    }
                }
            } else if ($id){

                if ($file_type == 'foir'){
                    ConsumerApplicationFiles::where('consumer_application_id', $id)->where('file_type','foir')->delete();
                }

                $consumer_application_file = new ConsumerApplicationFiles();
                $consumer_application_file->consumer_application_id = $id;
                $consumer_application_file->file_type = $file_type;
                $consumer_application_file->bank_name = $bank_name;
                $consumer_application_file->password = $password;
                $consumer_application_file->file_path = $file_path;
                $consumer_application_file->accounttype = $accounttype;
                $consumer_application_file->statementtype = $statementtype;
                $consumer_application_file->customer_id = $customerID;
                $consumer_application_file->bp_number = $BPNumber;
                $consumer_application_file->provider = $provider;
                $consumer_application_file->discom_district = $discom_district;
                $consumer_application_file->discom_mobile = $discom_mobile;
                $consumer_application_file->finbit_analysis_date = $finbit_analysis_date;
                $consumer_application_file->statemenfilettype = $statemenfilettype;
                $consumer_application_file->accountUID = $accountUID;
                $consumer_application_file->doc_ref_id = $doc_ref_id;
                if(isset($data['reference_id'])){
                    $consumer_application_file->doc_category = 'CKYC';
                }
                $consumer_application_file->created_by = (Auth::check()) ? Auth::user()->id : null;
                $consumer_application_file->image_score = $score;
                $consumer_application_file->m_generated = $m_generated;
                $consumer_application_file->bureau_report_type = $bureau_report_type;
                $consumer_application_file->bureau_report_score = $bureau_report_score;
                $consumer_application_file->is_masked = $masked == true && (strpos($file_type, 'aadhar_card') !== false || strpos($file_type, 'pan_card') !== false) ? 1 : 0;
                $consumer_application_file->applicant_type = $applicant_type;
                $consumer_application_file->save();
                $returnFileId = $consumer_application_file->id;

                if (isset($data['bank_name']) && isset($data['file_type']) && $data['bank_name'] && strpos($data['file_type'], 'bank_statement') !== false) {
                    (new FinBit(new Request()))->saveFraudReportDB($id, $consumer_application_file->id);
                }

                if (isset($data['provider'])) {
                    if (($customerID && $data['provider']) && (strpos($data['file_type'], 'electricity_bill') !== false || strpos($data['file_type'], 'gas_bill') !== false)) {
                        $data['file_id'] = $consumer_application_file->id;
                        (new KarzaAPI())->utilityValidation($data);
                    }
                }

                if ($file_type == "advance_amount_receipt"){
                    $tag = (new WebhookController())->getCommentTag([246934, 28]); // Jayashree & mahalaxmi disbursement tags
                    $commentText = $tag." Advance amount reciept is uploaded";
                    $comment = new Comments();
                    $comment->application_id = $id;
                    $comment->user_id = Auth::user()->id ?? 107;
                    $comment->comment = $commentText;
                    $comment->show_merchant = 0;
                    $comment->show_consumer = 0;
                    $comment->save();
                    $this->reviseDocsOnAdvanceReceiptUpload($id);
                }

                if ($file_type == "proforma"){
                    ConsumerApplicationFiles::where('consumer_application_id', $id)->where('show_to_merchant', 1)->where('file_type','pro_forma_invoice')->update(['show_to_merchant' => 2]);
                }
                if ($file_type == "pro_forma_invoice"){
                    ConsumerApplicationFiles::where('consumer_application_id', $id)->where('file_type', $file_type)->where('show_to_merchant', 1)->update(['show_to_merchant' => 0]);
                    ConsumerApplicationFiles::where('id', $returnFileId)->where('file_type', $file_type)->update(['show_to_merchant' => 1]);
                }
                // if ($show_to_merchant > 0){
                //     ConsumerApplicationFiles::where('id', $returnFileId)->where('file_type','pro_forma_invoice')->update(['show_to_merchant' => 1]);
                // }
                $consumerApplication = ConsumerApplication::where('id', $id)->first(['lender_id']);
                if($file_type_original && $consumerApplication->lender_id == AvanseServices::$lender_id) {
                    $this->addAvanseDocuments($id, $file_type_original, $file_path, $consumer_application_file->id, $uploaded_file);
                }

                $hypothecation_allowed = (isset($consumerApplication->lender_id) && in_array($consumerApplication->lender_id, explode(',',_env('HYPOTHECATION_LENDERS')))) ? true : false;

                // Initiate Hypothecation
                if ($hypothecation_allowed && (($file_type == "pro_forma_invoice" && (($created_by != null && $created_by != 107) || (isset($doc_ref_id) && $doc_ref_id == 'proforma by merchant'))) || ($file_type == "proforma" && $created_by == null))){
                    $apiController = new ApiController();
                    $request = new Request();
                    $request->merge(['id' => $id]);
                    $isHypothecationActive = $apiController->canHypothecated($id);
                    if ($isHypothecationActive) {
                        $loanHypothecationModel = LoanHypothecationModel::where('application_id', $id)->whereNull('deleted_at')->orderBy('created_at', 'desc')->first();
                        if (!isset($loanHypothecationModel->id)){
                            $apiController->initiateHypothecation($request);
                        }
                    }


                    $flag = 0;
                    if(_env('DIGIO_SIGNING') == 1) {
                        $flag = (new DigioHypothecation($request))->triggerHypothecationCommunication($request->get('id'));
                    }
                    if (!_env('DIGIO_SIGNING') == 1) {
                        $hypothecation = new LoanHypothecation($request);
                        $flag = $hypothecation->triggerHypothecationCommunication($id);
                    }
                    if($flag === 1) {
                        (new Slack(new Request(['title' => 'Hypothecation Agreement Not Fetched ', 'fields' => ['application_id' => $id], 'group' => Slack::$STAGE_TESTING])))->send();
                    }else if($flag === 2){
                        (new Slack(new Request(['title' => 'Hypothecation Agreement Already Signed ', 'fields' => ['application_id' => $id], 'group' => Slack::$STAGE_TESTING])))->send();
                    }else if($flag === 3){
                        (new Slack(new Request(['title' => 'Hypothecation Agreement Email Trigger Issue ', 'fields' => ['application_id' => $id], 'group' => Slack::$STAGE_TESTING])))->send();
                    }else {
                        (new Slack(new Request(['title' => 'Hypothecation Agreement Sent ', 'fields' => ['application_id' => $id], 'group' => Slack::$STAGE_TESTING])))->send();
                    }
                }
            }
        }else if ($ismerchant == 0 && $operation_type == 'lead') {
            if (isset($list[0]['path'])) {
                $existing_data = ProjectLeadFiles::where('lead_id', $id)->where('file_path', 'LIKE', '%' . $file_path . '%')->get(['file_path']);
                $existingfiles = array();
                foreach ($existing_data as $existingfile) {
                    array_push($existingfiles, $existingfile->file_path);
                }
                foreach ($list as $s3_files) {
                    if (!in_array($s3_files['path'], $existingfiles)) {
                        if ($setVisibility == 'public') {
                            $s3->setVisibility($s3_files['path'], 'public');
                        }
                        $consumer_application_file = new ProjectLeadFiles();
                        $consumer_application_file->lead_id = $id;
                        $consumer_application_file->file_type = $file_type;
                        $consumer_application_file->bank_name = $bank_name;
                        $consumer_application_file->password = $password;
                        $consumer_application_file->accounttype = $accounttype;
                        $consumer_application_file->statementtype = $statementtype;
                        $consumer_application_file->statemenfilettype = $statemenfilettype;
                        $consumer_application_file->file_path = $s3_files['path'];
                        $consumer_application_file->save();
                        $returnFileId = $consumer_application_file->id;
                    }
                }
            } else {
                $consumer_application_file = new ProjectLeadFiles();
                $consumer_application_file->lead_id = $id;
                $consumer_application_file->file_type = $file_type;
                $consumer_application_file->bank_name = $bank_name;
                $consumer_application_file->password = $password;
                $consumer_application_file->file_path = $file_path;
                $consumer_application_file->accounttype = $accounttype;
                $consumer_application_file->statementtype = $statementtype;
                $consumer_application_file->statemenfilettype = $statemenfilettype;
                $consumer_application_file->save();
                $returnFileId = $consumer_application_file->id;
            }
        } else {
            if (isset($list[0]['path'])) {

                if ($operation_type == 'merchant_location') {
                    $merchant_location = MerchantLocation::where('id', $id)->first(['merchant_id']);
                    if (isset($merchant_location->merchant_id)) {
                        $location_id = $id;
                        $id = $merchant_location->merchant_id;
                    }
                }

                if ($location_id) {
                    $existing_data = MerchantFiles::where('merchant_id', $id)->where('location_id', $location_id)->where('file_path', 'LIKE', $file_path . '%')->get(['file_path']);
                }else if ($operation_type == 'lead') {
                    $existing_data = MerchantFiles::where('merchant_id', $id)->where('type', 'lead')->where('file_path', 'LIKE', $file_path . '%')->get(['file_path']);
                } else {
                    $existing_data = MerchantFiles::where('merchant_id', $id)->whereNull('type')->where('file_path', 'LIKE', $file_path . '%')->get(['file_path']);
                }

                $existingfiles = array();
                foreach ($existing_data as $existingfile) {
                    array_push($existingfiles, $existingfile->file_path);
                }
                foreach ($list as $s3_files) {
                    if (!in_array($s3_files['path'], $existingfiles)) {
                        $consumer_application_file = new MerchantFiles();
                        $consumer_application_file->merchant_id = $id;
                        $consumer_application_file->location_id = $location_id;
                        $consumer_application_file->accounttype = $accounttype;
                        $consumer_application_file->statementtype = $statementtype;
                        $consumer_application_file->statemenfilettype = $statemenfilettype;
                        $consumer_application_file->type = $operation_type == 'lead' ? $operation_type : null;
                        $consumer_application_file->file_type = $file_type;
                        $consumer_application_file->file_path = $s3_files['path'];
                        $consumer_application_file->bank_name = $bank_name;
                        $consumer_application_file->accountUID = $accountUID;
                        $consumer_application_file->finbit_analysis_date = $finbit_analysis_date;
                        $consumer_application_file->password = $password;
                        $consumer_application_file->created_by = (Auth::check()) ? Auth::user()->id : null;
                        $consumer_application_file->save();
                        $returnFileId = $consumer_application_file->id;
                    }
                }
            } else {
                $consumer_application_file = new MerchantFiles();
                $consumer_application_file->merchant_id = $id;
                $consumer_application_file->location_id = $location_id;
                $consumer_application_file->type = $operation_type == 'lead' ? $operation_type : null;
                $consumer_application_file->accounttype = $accounttype;
                $consumer_application_file->statementtype = $statementtype;
                $consumer_application_file->statemenfilettype = $statemenfilettype;
                $consumer_application_file->file_type = $file_type;
                $consumer_application_file->file_path = $file_path;
                $consumer_application_file->bank_name = $bank_name;
                $consumer_application_file->finbit_analysis_date = $finbit_analysis_date;
                $consumer_application_file->accountUID = $accountUID;
                $consumer_application_file->password = $password;
                $consumer_application_file->created_by = (Auth::check()) ? Auth::user()->id : null;
                $consumer_application_file->save();
                $returnFileId = $consumer_application_file->id;
            }
        }

        if(strpos($file_type,'mandate') !== false || strpos($file_type,'esign') !== false || strpos($file_type,'sanction_letter') !== false || strpos($file_type,'pro_forma_invoice') !== false){
            return $returnFileId;
        }
        return '';
    }

    public function getUtilityBillValidation(Request $request){
        if($request->has('id') || $request->has('customer_id')){
            $file = ConsumerApplicationFiles::where('id', $request->get('id'))->first();
            if (isset($file)) { 
                $data['file_id'] = $file->id;
                $data['provider'] = $file->provider;
                $data['customerID'] = $file->customer_id;
                $data['id'] = $file->consumer_application_id;
                $data['file_type'] = $file->file_type;
                $data['district'] = isset($file->discom_district) ? $file->discom_district : null;
                $data['mobile_number'] = isset($file->discom_mobile) ? $file->discom_mobile : null;
                $data['user_id'] = $request->get('user_id');
            }
            if ($request->has('customer_id')) { // MConnect API snippet
                $data['customerID'] = $request->get('customer_id');
                $data['provider'] = $request->get('provider');
                $data['id'] = $request->get('application_id');
                $data['district'] = $request->has('district') ? $request->get('district') : '';
                $data['mobile_number'] = $request->has('mobile_number') ? $request->get('mobile_number') : '';
            }
            $status = (new KarzaAPI())->utilityValidation($data);
            if($status){
                return \response()->json(['status' => 'OK', 'message' => 'Successfully validated utility bill']);
            }
        }

        return \response()->json(['status' => 'FAIL', 'message' => 'Failed to validate utility bill']);
    }

    public function PTPDateNotification(){
        $promiseToPay = PromiseToPay::with('user','application.merchant','application.emi')->where('date', Carbon::now()->subDay(1)->toDateString())->get();

        $data[] = ['ID','PTP Date','PTP Tagged By','Customer Name', 'Email', 'Phone' , 'Merchant Name' ,'First EMI Date','Payment Received','Payment Received Date','Created At'];

        $totalSuccess = 0;
        $totalError = 0;

        $sent = [];
        if(count($promiseToPay)) {
            foreach ($promiseToPay as $item) {

                if($item->payment_received == 1){
                    $totalSuccess++;
                }else{

                    $data[] = [
                        'id' => $item->application->id,
                        'date' => $item->date,
                        'tagged_by' => $item->user->name,
                        'customer' => $item->application->name,
                        'email' => $item->application->email,
                        'phone' => $item->application->mobile_number,
                        'merchant_name' => $item->application->merchant->merchant_name,
                        'first_emi_date' => $item->application->emi->emi_date,
                        'payment_received' => $item->payment_received == 1 ? 'Yes' : 'No' ,
                        'payment_received_date' => $item->payment_received_date ? $item->payment_received_date : '-',
                        'created_at' => $item->created_at
                    ];

                    if(!in_array($item->application->id, $sent)) {
//                        $message = 'Dear ' . $item->application->name . '<br/>This is to inform you that you have failed your promise to pay your EMI amount. We would request you pay your pending amount as soon as possible to avoid late penalties & it will affect your bureaus.<br/>Kindly reach us at 8850077108 / 8928769161<br/>Regards<br/>Team Creditfair.';
                        $message = 'Dear ' . $item->application->name . '<br/>This is to inform you that you have failed your promise to pay your EMI amount. We would request you pay your pending amount as soon as possible to avoid late penalties & it will affect your bureau score. Kindly reach us at 8850077108 / 8928769161';
                        $entity = ['templateid' => '1307159973980425979', 'entityid' => Templates::$entityid];

                        if($item->application->mobile_number) {
                            send_sms($item->application->mobile_number, ['message'=>$message,'id'=>$item->application->id,'id_type'=>'application_id','templateId' => Templates::$failed_promise_emi_c1, 'args' => [$item->application->name], 'templateDetails' => $entity]);
                        }


                        if($item->application->email) {
                            Mail::send('emails.reminders.basic_reminder',
                                ['body' => $message]
                                , function ($message) use ($item) {
                                    $message->to([$item->application->email])->subject('You forgot to pay your EMI amount');
                                });
                        }

                        $sent[] = $item->application->id;
                    }

                    $totalError++;
                }
            }

            (new Slack(new Request(['title' => 'Promise To Pay', 'fields' => ['Total PTP Count' => count($promiseToPay), 'PTP Success' => $totalSuccess, 'PTP Failed' => $totalError, 'PTP Report Link' => 'Check email for report'], 'group' => 'payment_collection'])))->send();


            if($totalError) {
                $request = new Request(['data' => $data, 'sheet' => 'Sheet1']);

                $file = time() . 'Promise_To_Pay' . '.xlsx';

                Excel::store((new Exporter($request)), $file);

                Mail::send('emails.reminders.basic_reminder',
                    ['body' => 'Promise To Pay Data']
                    , function ($message) use ($file) {
                        $message->to(['payment@creditfair.in'])->subject('Promise To Pay Data ' . Carbon::now()->toDateString());
                        $message->attachData(file_get_contents(storage_path() . '/app/' . $file), $file);
                    });

            }

            JobProvider::where('from', 'PTPDate')->update(['is_available' => 0, 'available_at' => Carbon::now()->addDay(1)->toDateString() . ' 09:00']);

            return true;
        }
    }

    public function changeAdvisor(Request $request)
    {

        try {
            $change_advisor_id = $request->get('advisor_change');

            if ($change_advisor_id) {

                $application_id = $request->get('id');
                $application = ConsumerApplication::find($application_id);

                $adLogs = AdvisorLogs::where('application_id', $application_id)->where('status', 1)->first(['id']);
                if (isset($adLogs->id)) {
                    $advisorUpdate = AdvisorLogs::find($adLogs->id);
                    $advisorUpdate->status = 0;
                    $advisorUpdate->save();
                }

                $previous_advisor_id = $application->created_by;
                $hasPreAdvisorId = $application->pre_created_by;

                if (empty($previous_advisor_id)) {
                    $previous_advisor_id = $change_advisor_id;
                }
                $advisorLogs = new AdvisorLogs();
                $advisorLogs->application_id = $application_id;
                $advisorLogs->previous_advisor_id = $previous_advisor_id;
                $advisorLogs->current_advisor_id = $change_advisor_id;
                $advisorLogs->created_by = Auth::user()->id;
                $advisorLogs->status = 1;
                $advisorLogs->created_at = Carbon::now()->toDateTimeString();
                $advisorLogs->save();
                $status = 'OK';
                $message = 'Advisor changed successfully';

                $application->created_by = $change_advisor_id;

                if (!in_array($application->state, $this->statusreversearray['approved']) && ($hasPreAdvisorId == "" || $hasPreAdvisorId == null)) {
                    $application->pre_created_by = $previous_advisor_id;
                }

                $application->save();

                $this->sendChangeAdvisorEmail($change_advisor_id, $application_id);

                \Session::flash('success', $message);
            } else {
                $status = 'FAIL';
                $message = 'Please select advisor';
                \Session::flash('error', $message);
            }
        } catch (\Exception $e) {
            $status = 'FAIL';
            $message = 'Something went wrong';
            \Session::flash('error', $message);
        }
        return \response()->json(['status' => $status, 'message' => $message]);
    }

    public function sendChangeAdvisorEmail($user_id, $id)
    {
        try {
            $application = ConsumerApplication::find($id);
            $user = User::find($user_id);
            $body = 'Hi ' . $user->name . ',<br/><br/> You are the new advisor of ' . $application->name . ' case. ' . '<a href="https://creditfair.in/admin/consumer-applications/edit/' . $application->id . '">Click here</a> to check the application.';
            $subject = $application->name . ' case Advisor changed to ' . $user->name;
            $data = ['email' => $user->email, 'subject' => $subject];
            if (isset($user->email) && !empty($user->email)) {
                \Mail::send('emails.reminders.basic_reminder',
                    ['body' => $body]
                    , function ($message) use ($data) {
                        $message->to($data['email'])->subject($data['subject']);
                    });
            }
        } catch (\Exception $e) {

        }
    }

    public function generateEPFDocument($id, $body, $applicant_type = 1){

        $view = view('front.epf-report-panflow', ['body' => $body,'complete' => $this->array_flatten($body)]);

        $pdf = App::make('snappy.pdf.wrapper');
        $epf_report = $pdf->loadHTML($view);
        $epf_report->inline();
        $type = $applicant_type == 2 ? '-co-applicant' : '';
        $document = new ConsumerDocument(new Request());
        $document->uploadToS3('epf-report'.$type, $id, $epf_report->output());
        if (isset($body['result']['pdfLink']) && $body['result']['pdfLink']){
            $document->uploadToS3('epf-report-karza'.$type, $id, file_get_contents($body['result']['pdfLink']));
        }
    }

    public function generateGSTPANReport($id, $body, $type){
        $body = (array) $body;

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


        $name = $type == 1 ? $application->name : $application->co_applicant_name;
        $nameDoc = $type == 1 ? 'Applicant' : 'Co_Applicant';

        $view = view('front.gst-pan-report', ['body' => $body['result'], 'name' => $name]);

        $pdf = App::make('snappy.pdf.wrapper');
        $epf_report = $pdf->loadHTML($view);
        $document = new ConsumerDocument(new Request());
        $document->uploadToS3($nameDoc.'_GST_PAN_Report', $id, $epf_report->output());
    }

    public function generateBillValidation($data, $body){

        $view = view('front.bill-validation-report', ['body' => $body,'complete' => $this->array_flatten($body)]);

        $pdf = App::make('snappy.pdf.wrapper');
        $epf_report = $pdf->loadHTML($view);
        $document = new ConsumerDocument(new Request());
        $fileType = isset($data['file_type']) ? $data['file_type'] : 'electricity_bill';
        $document->uploadToS3($fileType.'_validation_report', $data['id'], $epf_report->output(), '.pdf', false, $data['customerID']);
        #take system name of applicant and co-app
        $consumerApplication = ConsumerApplication::where('id', $data['id'])->first();
        $resultArray = [];
        $applicantNamePercentage = 0;
        $coApplicantNamePercentage = 0;
        #check the percentage of match with applicant name
        if (isset($consumerApplication->name) && !empty($body['consumer_name'])) {
            //similar_text(strtolower($consumerApplication->name),strtolower($body['consumer_name']), $applicantNamePercentage);
            $matcher = new NameMatchService();
            $score = $matcher->nameMatch(strtolower($consumerApplication->name), strtolower($body['consumer_name']));
            $applicantNamePercentage = is_numeric($score) ? round($score, 2) : 0;
            $resultArray['applicant_match'] = round($applicantNamePercentage);
        }
        if (isset($consumerApplication->co_applicant_name) && !empty($body['consumer_name'])){
            //similar_text(strtolower($consumerApplication->co_applicant_name),strtolower($body['consumer_name']), $coApplicantNamePercentage);
            $matcher = new NameMatchService();
            $score = $matcher->nameMatch(strtolower($consumerApplication->co_applicant_name), strtolower($body['consumer_name']));
            $coApplicantNamePercentage = is_numeric($score) ? round($score, 2) : 0;
            $resultArray['co_applicant_match'] = round($coApplicantNamePercentage);
        }
        #check the percentage of match with co-app
        $record = ConsumerApplicationFiles::where('consumer_application_id',$data['id'])
            ->where('file_type', 'electricity_bill')->orderByDesc('created_at')
            ->first();

        if ($record && count($resultArray) > 0) {
            $record->ebill_name_verify = json_encode($resultArray); // Assign JSON string to the column
            $record->save(); // Save changes to the database
        }
        #save the data
    }

    public function array_flatten($array) {
        if (!is_array($array)) {
            return FALSE;
        }
        $result = array();
        foreach ($array as $key => $value) {
            if (is_array($value)) {
                $result = array_merge($result, $this->array_flatten($value));
            }
            else {
                $result[$key] = $value;
            }
        }
        return $result;
    }

    public function handleKarzaAuthStatusCodes($request, $response){
        $status_code_reasons = array('102'=>'Invalid ID number or combination of inputs',
            '103'=>'No records found for the given ID or combination of inputs',
            '104'=>'Max retries exceeded',
            '105'=>'Missing Consent',
            '106'=>'Multiple Records Exist',
            '107'=>'Not Supported',
            '108'=>'Internal Resource Unavailable',
            '109'=>'Too many records Found');
            $reason = isset($response['status-code']) ? $status_code_reasons[$response['status-code']]: "";
            $failure_log = new EpfFailureLog();
                        $failure_log->application_id = $request->get('id');
                        $failure_log->request = json_encode($request);
                        $failure_log->response = json_encode($response);
                        $failure_log->status_code = isset($response['status-code']) ? $response['status-code'] : 0;
                        $failure_log->reason = $reason;
                        $failure_log->created_at = Carbon::now()->toDateTimeString();
                        $failure_log->applicant_type = $request->get('type');
                        $failure_log->save();
        return $reason;
}

    public function employmentVerificationAdvanced(Request $request){
        $message = 'Employment verification failed';
        $verificationData = Null;
        $status = 'Failed';
        $reason = "";
        
        try {
            $applicationId = $request->get('id');
            $applicantType = $request->get('type');

            if (!$this->validateSolarEligibility($applicationId, $applicantType)) {
                 return response()->json([
                    'status' => 'Failed', 
                    'message' => 'EPF Failed.', 
                    'reason' => 'Eligibility Check Failed', 
                    'type' => $applicantType
                ]);
            }
            // ------------------------------------

            $epfUAN = new EPFUANLookup();
            $response = $epfUAN->employmentVerificationAdvancedPanFlow(
                $request->get('employerName'), 
                $request->get('employeeName'), 
                $request->get('emp_entity_id'), 
                $request->get('uan_no'), 
                $request->get('emp_mobile'), 
                $request->get('emp_email'), 
                $applicationId, 
                $applicantType
            );

            if ($response && (!isset($response['status-code']) || $response['status-code'] != 101)) {
                $reason = $this->handleKarzaAuthStatusCodes($request, $response);
            } elseif ($response && isset($response['status-code']) && $response['status-code'] == 101 && isset($response['result']) && $response['result']) {

                $this->generateEPFDocument($applicationId, $response, $applicantType);

                $status = 'OK';
                $message = 'Employment verification done';
                $verificationData = json_encode($response);
                
                EPFUANLookup::where('application_id', $applicationId)->where('applicant_type', $applicantType)->delete();
                
                EPFUANLookup::insert([
                    'application_id' => $applicationId,
                    'entity_id' => $request->get('emp_entity_id'),
                    'uan_no' => $request->get('uan_no'),
                    'email' => $request->get('emp_email'),
                    'mobile' => $request->get('emp_mobile'),
                    'employerName' => $request->get('employerName'),
                    'employeeName' => $request->get('employeeName'),
                    'data' => $verificationData,
                    'applicant_type' => $applicantType,
                    'created_at' => Carbon::now()->toDateTimeString()
                ]);
            }
            return response()->json(['status' => $status, 'message' =>  $message, 'reason'=> $reason, 'type' => $applicantType]);
        } catch (\Exception $e) {
            (new Slack(new Request(['title' => 'Employment Verification Failed', 'fields' => ['error' => $e->getMessage(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString(), 'application_id' => $request->get('id'), 'id_type' => 'application_id'], 'group' => Slack::$STAGE_TESTING])))->send();
        }

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

    private function validateSolarEligibility($applicationId, $applicantType){
        $app = ConsumerApplication::with(['application_element'])
            ->where('id', $applicationId)
            ->first(['id', 'pan_card', 'co_applicant_pan_card', 'employee_status', 'purpose', 'co_applicant_employee_status']);

        if ($app->purpose != _env('SOLAR_CATEGORY_ID')) {
            $this->logEpfFailure($applicationId, $applicantType, 'Purpose mismatch: ' . $app->purpose . ' (Expected 24)');
            return false;
        }

        if ($applicantType == 1){
            if (strtoupper($app->employee_status) !== 'SALARIED') {
                $this->logEpfFailure($applicationId, $applicantType, 'Employment Status mismatch: ' . $app->employee_status);
                return false;
            }
            if (empty($app->pan_card)) {
                $this->logEpfFailure($applicationId, $applicantType, 'Missing Applicant PAN');
                return false;
            }
        }

        if ($applicantType == 2){
            if (strtoupper($app->co_applicant_employee_status) !== 'SALARIED') {
                $this->logEpfFailure($applicationId, $applicantType, 'Co-applicant Employment Status mismatch: ' . $app->co_applicant_employee_status);
                return false;
            }
            if (empty($app->co_applicant_pan_card)) {
                $this->logEpfFailure($applicationId, $applicantType, 'Missing Co Applicant PAN');
                return false;
            }
        }

        $element = $app->application_element;

        if ($element->type_of_customer != 1) {
            $this->logEpfFailure($applicationId, $applicantType, 'Customer Type mismatch: Not Residential (1)');
            return false;
        }

        if (strtoupper($element->type_of_customer_application) !== 'INDIVIDUAL') {
            $this->logEpfFailure($applicationId, $applicantType, 'User Type mismatch: Not INDIVIDUAL');
            return false;
        }

        return true;
    }

    private function logEpfFailure($applicationId, $applicantType, $reason){
        $failure_log = new EpfFailureLog();
        $failure_log->application_id = $applicationId;
        $failure_log->request = json_encode(['check' => 'Solar Eligibility Validation']);
        $failure_log->response = json_encode(['status' => 'Validation Failed']);
        $failure_log->status_code = 418;
        $failure_log->reason = $reason;
        $failure_log->created_at = Carbon::now()->toDateTimeString();
        $failure_log->applicant_type = $applicantType;
        $failure_log->save();
    }

    public function employmentVerification(Request $request){

        $isVerified = 0;
        $status = 'OK';
        $message = $_message = 'UAN number is verified';
        $_uan = [];
        try {
            $mobile_number = $request->get('mobile_number');
            if ($request->get('id') && $mobile_number) {

                $applicationElement = ConsumerApplicationElement::where('application_id', $request->get('id'))->first();
                if (!isset($applicationElement->id)) {
                    $applicationElement = new ConsumerApplicationElement();
                }

                $epfUAN = new EPFUANLookup();

                if (!$request->get('uan')) {

                    $application = ConsumerApplication::find($request->get('id'));
                    if ($application->mobile_number != $mobile_number) {
                        $application->mobile_number = $mobile_number;
                        $application->save();
                    }

                    $response = (new EPFUANLookup())->getUAN($mobile_number);

                    if ($response && isset($response['status-code']) && $response['status-code'] == 101 && isset($response['result']) && $response['result']) {
                        $applicationElement->uan_number = json_encode($response['result']);
                        $applicationElement->save();
                        foreach ($response['result']['uan'] as $uan) {
                            $isVerified = $this->grabDetails($epfUAN, $uan, $mobile_number, $applicationElement, $request);
                            if(isset($isVerified['error'])){
                                $message = $isVerified['error'];
                                break;
                            }
                            $_uan[] = $uan;
                        }
                    }else if(isset($response['error'])){
                        $message = $response['error'];
                    }
                } else if ($request->get('uan')) {
                    $isVerified = $this->grabDetails($epfUAN, $request->get('uan'), $mobile_number, $applicationElement, $request);
                    if(isset($isVerified['error'])){
                        $message = $isVerified['error'];
                    }
                    $_uan[] = $request->get('uan');
                }
            }
        }catch (\Exception $e){
            $status = 'FAIL';
            $message = 'Something went wrong';
        }

        if(!$isVerified){
            if($_message == $message)
                $message = 'UAN number is invalid';
        }

        return \response()->json(['status' => $status, 'message' =>  $message, 'uan' => implode(',',$_uan), 'is_verified' => $isVerified]);
    }

    public function grabDetails(EPFUANLookup $epfUAN, $uan, $mobile_number, ConsumerApplicationElement $applicationElement, Request $request){
        $isVerified = 0;
        $response = $epfUAN->verifyUAN($uan);
        if ($response && isset($response['status-code']) && $response['status-code'] == 101 && isset($response['result']) && $response['result']) {
            $result = json_encode($response['result']);
            EPFUANLookup::insert([
                'application_id' => $request->get('id'),
                'mobile_number' => $mobile_number,
                'data' => $result,
                'created_at' => Carbon::now()->toDateTimeString()
            ]);
            if(isset($response['result'][0]) && isset($response['result'][0]['membershipId'])) {
                $applicationElement->uan_verified = 1;
                $applicationElement->save();
                $isVerified = 1;
            }
        }else if(isset($response['error'])){
            return ['error' => $response['error']];
        }

        return $isVerified;
    }

    public function changeLoanApplicationNumber($consumer_application, Request $request)
    {
        $invoice = ProFormaInvoice::where('application_id', $consumer_application->id)->first(['id']);
        if (isset($invoice->id)) {
            $merchant = Merchant::where('id', $request->get('merchant_id'))->first(['is_collected', 'slug','id']);
            $invoice->fill(Input::all());
            $invoice->processing_fee_by_merchant = ((new AvanseProcesses(new Request(['id' => $consumer_application->id])))->checkEligibility() ? 1 : isset($merchant->is_collected)) ? $merchant->is_collected : 0;
            $invoice->processing_fee_by_merchant = isset($merchant->is_collected) ? $merchant->is_collected : 0;
            $invoice->loan_application_no = $this->getLoanApplicationID($consumer_application->id, $merchant);
            $invoice->update();
        }
    }

    public function getFullName($reqeust){
        return trim($reqeust->get('first_name').' '.$reqeust->get('middle_name').' '.$reqeust->get('last_name'));
    }

    public function getEditPostConsumerApplication(Request $request, $id)
    {
        $actionType = $request->input('action_type'); // Get the action type
        $foir_changed = $request->input('foir_changed');

        if ($request->has('documents') && count(array_diff($request->get('documents'), [null]))) {
            if(isset($request->fileNamePDF)){
                foreach($request->fileNamePDF as $_key => $fileArray){
                    if ($_key == 'electricity_bill') {
                        $electricityBillUpload = 1;
                        $electricityNameChangeVal = $request->input('electricityNameChange');
                        if (!is_null($electricityNameChangeVal)) {
                            $request->merge(['electricity_name_change' => $electricityNameChangeVal[0]]);
                        }
                    }
                    foreach ($fileArray as $__key => $file) {
                        if(filesize($file) > 18874368){
                            \Session::flash('error2', 'Uploaded file is too large');
                            return redirect()->back();
                        }
                    }
                }
            }
            $documentStatus = $this->uploadConsumerDocuments($request, $id);
        }

        // Validation rules for edit post consumer application
        $baseRules = [
            "first_name" => "nullable|string",
            "middle_name" => "nullable|string",
            "last_name" => "nullable|string",
            "gender" => "nullable|string",
            "email" => "required|string|regex:/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[_a-z0-9-]+)*(\.[a-z]{2,})$/i",
            "co_applicant_email" => "nullable|string|regex:/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[_a-z0-9-]+)*(\.[a-z]{2,})$/i",
            "emp_email" => "nullable|string|regex:/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[_a-z0-9-]+)*(\.[a-z]{2,})$/i",
            "merchant_representative_email" => "nullable|string|regex:/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[_a-z0-9-]+)*(\.[a-z]{2,})$/i",
            "mobile_number" => "required|numeric|digits:10",
            "co_applicant_mobile_number" => "nullable|numeric|digits:10",
            "emp_mobile" => "nullable|numeric|digits:10",
            "merchant_id" => "required|numeric",
            "purpose" => "required",
            "dob" => ['required',function ($attribute, $value, $fail) {
                $age=Carbon::parse($value)->diff(Carbon::now())->y;
                if($age>=65){
                    $fail('Age over 64. Applicants is '.$age.' years are ineligible for loans');
                }
            }],
        ];

        // For merchant_v2 user type, relax some required rules
        if (Auth::check() && Auth::user()->user_type == UserTypes::$merchant_v2) {
            $baseRules['email'] = "string|regex:/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[_a-z0-9-]+)*(\.[a-z]{2,})$/i";
            $baseRules['mobile_number'] = "numeric|digits:10";
        }

        $validation = Validator::make($request->all(), $baseRules, [
            "string" => ":attribute is not string",
            "digits" => ":attribute is not in proper length",
            "numeric" => ":attribute is not number",
            "required" => ":attribute is required",
        ]);
        if($validation->messages()->all()){
            $data = [
                "status" => "FAIL",
                "message" => $validation->messages()->all(),
                "error" => [
                    "code" => "400",
                    "message" => "Bad Request"
                ]
            ];
            \Session::flash('error', json_encode($data['message']));
            return redirect()->back();
        }

        $reasons = [];
        $consumer_application = ConsumerApplication::find($id);

        // --- START: KYC CHANGE DETECTION LOGIC ---
        $this->detectAndResetKYC($request, $consumer_application, $id);

        // 1. Check for Duplicate Mobile Numbers
        $req_mobile = $request->get('mobile_number');
        $req_co_mobile = $request->get('co_applicant_mobile_number');

        if (!empty($req_co_mobile) && $req_mobile == $req_co_mobile) {
            \Session::flash('error', 'Applicant and Co-Applicant cannot share the same Mobile Number.');
            return redirect()->back()->withInput();
        }

        // 2. Check for Duplicate PAN Cards
        $app_pan = $request->get('pan_card') ? $request->get('pan_card') : $consumer_application->pan_card;
        $co_app_pan = $request->get('co_applicant_pan_card') ? $request->get('co_applicant_pan_card') : $consumer_application->co_applicant_pan_card;

        if (!empty($co_app_pan) && !empty($app_pan)) {
            if (strtoupper(trim($app_pan)) === strtoupper(trim($co_app_pan))) {
                \Session::flash('error', 'Applicant and Co-Applicant cannot share the same PAN Card.');
                return redirect()->back()->withInput();
            }
        }

        if($consumer_application->lender_id == Singularity::$lender_id && $this->homevill_callback){
            if(!isset($this->homevill_callback->documentUrl)){

                $homeVilleErrorMessage = '';
                $errorHomeVille = $this->homevill_callback->getData();
                if(isset($errorHomeVille->message) && is_string($errorHomeVille->message)){
                   $homeVilleErrorMessage = $errorHomeVille->message;
                }else if(isset($errorHomeVille->data->Error)){
                    foreach($errorHomeVille->data->Error as $index => $error){
                        $homeVilleErrorMessage .= $error[0]."\n";
                    }
                }

                \Session::flash('error_homeville', 'HomeVille: '.$homeVilleErrorMessage ?? 'HomeVille Error!');
                return redirect()->back();
            }
        }

        if($request->get('mobile_number') != $consumer_application->mobile_number){
            User::where('id', $consumer_application->user_id)->update(['mobile_number'=> $request->get('mobile_number')]);
        }

        $this->updateSanctionAmount($id, $consumer_application, $request);

        (new ContentLogger())->logger($consumer_application, 'consumer_application');

        $paddress1 = str_replace("'","", str_replace('"','', $request->per_address_1));
        $paddress2 = str_replace("'","", str_replace('"','', $request->per_address_2));
        $paddress3 = str_replace("'","", str_replace('"','', $request->per_address_3));
        $request->merge(['permanent_address_line_1' => $paddress1.$paddress2.$paddress3]);
        // $request->merge(['permanent_address_line_1' => str_replace("'","", str_replace('"','', $request->permanent_address_line_1))]);
        $request->merge(['permanent_address_city' => str_replace("'","", str_replace('"','', $request->permanent_address_city))]);
        $request->merge(['permanent_address_landmark' => str_replace("'","", str_replace('"','', $request->permanent_address_landmark))]);
        $curddress1 = str_replace("'","", str_replace('"','', $request->cur_address_1));
        $curddress2 = str_replace("'","", str_replace('"','', $request->cur_address_2));
        $curddress3 = str_replace("'","", str_replace('"','', $request->cur_address_3));
        $request->merge(['current_address_line_1' => $curddress1.$curddress2.$curddress3]);
        // $request->merge(['current_address_line_1' => str_replace("'","", str_replace('"','', $request->current_address_line_1))]);
        $request->merge(['current_address_city' => str_replace("'","", str_replace('"','', $request->current_address_city))]);
        $request->merge(['current_address_landmark' => str_replace("'","", str_replace('"','', $request->current_address_landmark))]);
        $waddress1 = str_replace("'","", str_replace('"','', $request->work_address_1));
        $waddress2 = str_replace("'","", str_replace('"','', $request->work_address_2));
        $waddress3 = str_replace("'","", str_replace('"','', $request->work_address_3));
        $request->merge(['work_address_line_1' => $waddress1." ".$waddress2." ".$waddress3]);
        // $request->merge(['permanent_address_line_1' => str_replace("'","", str_replace('"','', $request->permanent_address_line_1))]);
        $request->merge(['work_address_city' => str_replace("'","", str_replace('"','', $request->work_address_city))]);
        $co_app_added = false;
        if (empty($consumer_application->co_applicant_name) && ($request->has('co_applicant_name') && !empty($request->get('co_applicant_name')))) {
            $ConsumerApplication = new ConsumerApplication();
            $ConsumerApplication->fill($request->input());
            $customer = $ConsumerApplication->saveCustomer();
            
            $co_app_added = true;
         
            if (!$consumer_application->applicant_id) {
                $consumer_application->applicant_id = $customer->applicant_id;
            }
            $consumer_application->co_applicant_id = $customer->co_applicant_id;
        }

        $cwFactory = new CloudWatchLoggerFactory();
        
        // Check for collision (Both IDs exist and are identical)
        $appId = $consumer_application->applicant_id;
        $coAppId = $consumer_application->co_applicant_id;
        $collision = (!empty($appId) && !empty($coAppId) && $appId == $coAppId);

        $logData = array(
            'action' => 'POST_CO_APPLICANT_UPDATE_CHECK',
            'application_id' => $id, 
            'user_id' => Auth::id() ?? 'system',
            'co_app_was_added_flag' => $co_app_added,
            'current_applicant_id' => $appId,
            'current_co_applicant_id' => $coAppId,
            'ID_COLLISION_DETECTED' => $collision ? 'YES - CRITICAL ERROR' : 'NO',
            'message' => 'Verifying applicant and co-applicant IDs after update logic'
        );
        $cwFactory->logger(json_encode($logData));

        if($name = $this->getFullName($request)) {
            $consumer_application->name = $name;
        }


        if ($request->has('merchant_id') && $consumer_application->merchant_id != $request->get('merchant_id')) {
            $this->changeLoanApplicationNumber($consumer_application, $request);
        }

        $loan_amount = $consumer_application->loan_amount;
        $application_status = $consumer_application->state;

        if ($loan_amount != $request->get('loan_amount') && in_array($application_status, ['waiting for documents', 'in-process'])) {
            $jobView = JobProvider::where('from', 'statusChange')->where('application_id', $id)->where('payload', 'like', '%"status":"'.$application_status.'"%')->where('is_available', 0)->first(['id']);
            $statusFlag = $application_status;
            if (!isset($jobView->id)) {
                $statusFlag = $application_status == 'waiting for documents' ? 'in-process' : $application_status;
            }
            $this->rollbackJobChanges(['application_id' => $id], $statusFlag, [$statusFlag]);
            if (!isset($jobView->id)) {
                $this->startEscalation($id, $application_status, $request->get('loan_amount'));
            }
        }

        if ($request->has('approved_amount')) {
            $this->generateEMIIFRequired($request, $consumer_application, $id);
        }

        if ($consumer_application->permanent_address_line_1 || $consumer_application->current_address_line_1 || $consumer_application->work_address_line_1) {
            $service = [];
        if ($consumer_application->permanent_address_line_1 != $request->get('permanent_address_line_1')) {
                $service[] = 'permanent';
            }
            if ($consumer_application->current_address_line_1 != $request->get('current_address_line_1')) {
                $service[] = 'current';
            }
            if ($consumer_application->work_address_pincode != $request->get('work_address_pincode')) {
                $service[] = 'work';
            }
            if ($service) {
                UserGeolocation::where('_id', $consumer_application->id)->where('id_type', 'application_id')->whereIn('service', $service)->delete();
            }
        }

        $permanent_address = $consumer_application->permanent_address_line_1.' '.$consumer_application->permanent_address_landmark.' '.$consumer_application->permanent_address_state.' '.$consumer_application->permanent_address_city.' '.$consumer_application->permanent_address_pincode;
        $permanent_address_request = $request->get('permanent_address_line_1').' '.$request->get('permanent_address_landmark').' '.$request->get('permanent_address_state').' '.$request->get('permanent_address_city').' '.$request->get('permanent_address_pincode');

        $cap = $consumer_application->current_address_pincode;
        $pap = $consumer_application->permanent_address_pincode;
        $wap = $consumer_application->work_address_pincode;
        $caap = $consumer_application->co_applicant_address_pincode;

        $approved_amount = $consumer_application->approved_amount;
        
        $isAmountChanged = $request->has('approved_amount') && $request->get('approved_amount') != $approved_amount;
        $oldApprovedAmount = $approved_amount;
        $offer_id = $consumer_application->offer_id;
        if (!empty($consumer_application->state) && !in_array($consumer_application->state,['incomplete form', 'form completed', 'waiting for decision', 'waiting for documents', 'in-process'])) {
            if (!\Illuminate\Support\Facades\Session::has('post_approval_edit_loan_amount|-0')) {
                $request->merge(['loan_amount' => $consumer_application->loan_amount]);
            }
            if (!\Illuminate\Support\Facades\Session::has('post_approval_edit_communication_mobile_number|-3')) {
                $request->merge(['mobile_number' => $consumer_application->mobile_number]);
            }
            if (!\Illuminate\Support\Facades\Session::has('post_approval_edit_tenure|-2')) {
                $request->merge(['offer_id' => $consumer_application->offer_id]);
            }
        }

        $this->updateCachedExistingCustomer($consumer_application, $request);

        $consumer_application->fill($request->input());
        $mobile_changed = $consumer_application->isDirty('mobile_number');
        $co_app_mobile_changed = $consumer_application->isDirty('co_applicant_mobile_number');

        if($request->has('linkedin') && $request->get('linkedin')){
            $checklist = Checklist::where('application_id', $id)->first(['id']);
            if (isset($checklist->id)) {
                Checklist::where('application_id', $id)->update(['linkedin' => $request->get('linkedin')]);
            }else{
                Checklist::insert(['application_id' =>  $id, 'linkedin' => $request->get('linkedin')]);
            }
        }

        if ($request->has('company_name_search')) {
            if (!empty($request->get('company_name_search'))) {
                $companyName = Company::where('company', $request->get('company_name_search'))->first();
                if(!isset($companyName->id)) {
                    $CompanyID = Company::insertGetId([
                        'category' => 'CAT D',
                        'company' => $request->get('company_name_search'),
                    ]);
                }else{
                    $CompanyID = isset($companyName->id) ? $companyName->id : 0;
                }
                $consumer_application->company_name = isset($CompanyID) ? $CompanyID : 0;
            }
        }

        if ($request->has('co_applicant_company_name_search')) {
            if (!empty($request->get('co_applicant_company_name_search'))) {
                $companyName = Company::where('company', $request->get('co_applicant_company_name_search'))->first();
                if(!isset($companyName->id)) {
                    $CompanyID = Company::insertGetId([
                        'category' => 'CAT D',
                        'company' => $request->get('co_applicant_company_name_search'),
                    ]);
                }else{
                    $CompanyID = isset($companyName->id) ? $companyName->id : 0;
                }
                $consumer_application->co_applicant_company_name = isset($CompanyID) ? $CompanyID : 0;
            }
        }

        if ($consumer_application->created_by == 0 || $consumer_application->created_by == null) {
            $consumer_application->created_by = Auth::user()->id;
        }

        if($approved_amount > 0 && $request->get('approved_amount') == 0){
            $consumer_application->approved_amount = $approved_amount;
        }

        $consumer_application->dob = date("Y-m-d", strtotime($consumer_application->dob));
        $consumer_application->co_applicant_dob = date("Y-m-d", strtotime($consumer_application->co_applicant_dob));

        if ($request->has('offer_id') && $request->get('offer_id')) {
            $merchantOffer = MerchantOffers::where('id', $request->get('offer_id'))->first(['tenure', 'advance_type', 'advance_emi']);
            $consumer_application->tenure = isset($merchantOffer->tenure) ? $merchantOffer->tenure : 0;
        }
        if ($request->has('offer_id') && !isset($offer_id)) {
            $initial_offer_id = $request->get('offer_id');
        }else{
            $initial_offer_id = 0;
        }

        if (!empty($request->get('cpv_longitude')) && !empty($request->get('cpv_latitude'))) {
            $this->saveUserGeolocation($consumer_application, ['applicant_type' => 1, 'id_type' => 'application_id', 'service' => 'cpv', 'longitude' => $request->get('cpv_longitude'), 'latitude' => $request->get('cpv_latitude')]);
        } else {
            //UserGeolocation::where('_id', $consumer_application->id)->where('id_type', 'application_id')->where('service', 'cpv')->delete();
        }
        
        $consumer_application->save();

        if ($loan_amount != $request->get('loan_amount')) {
            $disbCtrl = new DisbursementController(new Request());
            $disbCtrl->getCersaiHypothecationCharge($consumer_application, true);
        }

        if($request->has('reference_id') && !empty($request->get('reference_id'))){
            $this->initiateCKYC($request ,$id);
        }

        // auto generate CAM report on permanent address change but not on tenure or approved amount change
        if(($consumer_application->state == 'approved') || ($consumer_application->state == 'disbursement checklist done') || ($consumer_application->state == 'ready for disbursement')){
            if(($permanent_address != $permanent_address_request) || ($permanent_address == $permanent_address_request)){
                if((($offer_id != $request->get('offer_id')) || ($approved_amount != $request->get('approved_amount')))){
                    \Session::flash('error', 'Please generate new EMI plan as you have changed tenure or approved amount');
                }
            }
            if((($offer_id == $request->get('offer_id')) && ($approved_amount == $request->get('approved_amount'))) && ($permanent_address != $permanent_address_request)){
                event(new EventPostCreateCustomer($consumer_application->id,'createCamReportCommand'));
            }
        }

        if(($request->get('current_address_pincode') && $cap != $request->get('current_address_pincode')) ||
            ($request->get('permanent_address_pincode') &&  $pap != $request->get('permanent_address_pincode')) ||
            ($request->get('work_address_pincode') && $wap != $request->get('work_address_pincode')) ||
            ($request->get('co_applicant_address_pincode') && $caap != $request->get('co_applicant_address_pincode'))) {
            $this->checkApprovedPinCode($id, true);
        }

        $this->updateAvanseCIF($id, $consumer_application, $request);


        $applicationElementArray = [
            'application_id' => $id,
            'industry' => $request->get('industry'),
            'profession_type' => $request->get('profession'),
            'co_applicant_industry' => $request->get('co_applicant_industry'),
            'co_applicant_profession_type' => $request->get('co_applicant_profession'),
            'work_email' => $request->get('work_email'),
            'center_id' => $request->get('center_id'),
            'gst_number' => $request->get('gst_number'),
            'designation' => $request->get('designation'),
            'department' => $request->get('department'),
            'contact' => $request->get('contact'),
            'product_id' => $request->get('product_id'),
            'product_name' => $request->get('product_name') && is_array($request->get('product_name')) ? implode(',',$request->get('product_name')) : $request->get('product_name'),
            'duration' => $request->get('duration_month') . '|' . $request->get('duration_year'),
            'preferred_language' => $request->get('preferred_language'),
            'collection_advisor' => $request->has('collection_advisor') && $request->get('collection_advisor') > 0 ? $request->get('collection_advisor') : 0,
            'co_applicant_for_signing' => ($request->has('co_applicant_for_signing')) ? 1 : 2,
            'co_applicant_for_income' => ($request->has('co_applicant_for_income')) ? 1 : 2,
            'reference_name_1' => $request->get('reference_name_1'),
            'reference_name_2' => $request->get('reference_name_2'),
            'reference_contact_1' => $request->get('reference_contact_1'),
            'reference_contact_2' => $request->get('reference_contact_2'),
            'reference_relation_1' => $request->get('reference_relation_1'),
            'reference_relation_2' => $request->get('reference_relation_2'),
            'video_kyc' => $request->get('video_kyc'),
            'admission_status' => $request->get('admission_status'),
            'is_comm_no_linked_to_aadhar' => $request->get('is_comm_no_linked_to_aadhar'),
            'aadhar_linked_mobile' => $request->get('aadhar_linked_mobile'),
            'coapp_is_comm_no_linked_to_aadhar' => $request->get('coapp_is_comm_no_linked_to_aadhar'),
            'coapplicant_aadhar_linked_mobile' => $request->get('coapplicant_aadhar_linked_mobile'),
            'type_of_entity' => $request->get('type_of_entity'),
        ];

        if ((!empty($consumer_application->state) && !in_array($consumer_application->state,['incomplete form', 'form completed', 'waiting for decision', 'waiting for documents', 'in-process'])) && !\Illuminate\Support\Facades\Session::has('post_approval_edit_product_name|-1')) {
            unset($applicationElementArray['product_name']);
        }

        $this->updateProformaAttributes($id, $request);

        $applicationElementObject = ConsumerApplicationElement::where('application_id', $id)->first();
        $applicationAdditionObject = ConsumerApplicationAdditional::where('application_id', $id)->first();
        if (!isset($applicationAdditionObject->id)) {
            $applicationAdditionObject = new ConsumerApplicationAdditional();
            $applicationAdditionObject->application_id = $id;
        }
        if (!isset($applicationElementObject->id)) {
            $applicationElementObject = new ConsumerApplicationElement();
            $applicationElementObject->application_id = $id;
        } else {

            Logs::d($applicationElementObject->toArray());

            if (isset($applicationElementArray['co_applicant_for_income']) && isset($applicationElement->id) && $applicationElementArray['co_applicant_for_income'] != $applicationElementObject->co_applicant_for_income) {
                $coapplicantsiging = new CoApplicateValidationLog();
                $coapplicantsiging->application_id = $id;
                $coapplicantsiging->user_id = Auth::user()->id;
                $coapplicantsiging->co_applicant_type = "Income";
                $coapplicantsiging->previous_tatus = $applicationElementObject->co_applicant_for_income;
                $coapplicantsiging->new_status = $applicationElementArray['co_applicant_for_income'];
                $coapplicantsiging->save();
            }

            if (isset($applicationElementArray['co_applicant_for_signing']) && isset($applicationElement->id) && $applicationElementArray['co_applicant_for_signing'] != $applicationElementObject->co_applicant_for_signing) {
                $coapplicantsiging = new CoApplicateValidationLog();
                $coapplicantsiging->application_id = $id;
                $coapplicantsiging->user_id = Auth::user()->id;
                $coapplicantsiging->co_applicant_type = "Signing";
                $coapplicantsiging->previous_tatus = $applicationElementObject->co_applicant_for_signing;
                $coapplicantsiging->new_status = $applicationElementArray['co_applicant_for_signing'];
                $coapplicantsiging->save();
            }

            /*if (empty($applicationElementArray['center_id'])) {
                $applicationElementArray['center_id'] = 0;
            }*/

            //ConsumerApplicationElement::where('application_id', $id)->update($applicationElementArray);
        }


        $product_name = $request->get('product_name') && is_array($request->get('product_name')) ? implode(',',$request->get('product_name')) : $request->get('product_name');
        if(!$product_name){
            $product_name = $request->get('product_name_str') ? $request->get('product_name_str') : '';
        }

        if ($applicationElementObject->co_applicant_for_signing != 1 && $request->has("co_applicant_for_signing")) {
            $reasons[] = 'signing';
        }

        if ($applicationElementObject->co_applicant_for_income != 1 && $request->has("co_applicant_for_income")) {
            $reasons[] = 'income';
        }

        if ($applicationAdditionObject->co_applicant_required_for_mandate != 1 && $request->has("co_applicant_required_for_income_and_mandate")) {
            $reasons[] = 'mandate';
        }

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

            $this->webhook($id, [
                'merchant_id' => $consumer_application->merchant_id,
                'type' => 'Application-Webhook',
                'status' => $webhookStatus,
                'data' => $this->getMConnectPayload($id, $webhookStatus, $addn_data)
            ]);
        }

        $reference_number = $applicationElementObject->reference_number;
        $applicationElementObject->installation_address_city = $request->has('installation_address_city') ? $request->get('installation_address_city') : "";
        $applicationElementObject->installation_address_state = $request->has('installation_address_state') ? $request->get('installation_address_state') : "";
        $applicationElementObject->installation_address_pincode = $request->has('installation_address_pincode') ? $request->get('installation_address_pincode') : "";
        $applicationElementObject->installation_address_status = $request->has('installation_address_status') ? $request->get('installation_address_status') : "";
        $applicationElementObject->installation_address_landmark = $request->has('installation_address_landmark') ? $request->get('installation_address_landmark') : "";
        $applicationElementObject->installation_address_line_1 = ($request->has('installation_address_1') ? $request->get('installation_address_1') : "") . '' .($request->has('installation_address_2') ? $request->get('installation_address_2') : "") . '' .($request->has('installation_address_3') ? $request->get('installation_address_3') : "");

        if ($request->has('type_of_customer_sub_category')) {
            $request->merge([
                'type_of_customer_sub_category' => html_entity_decode($request->get('type_of_customer_sub_category'))
            ]);
        }

        $applicationElementObject->fill($request->all());
        $applicationElementObject->applicant_caste = $request->get('applicant_caste');
        $applicationElementObject->applicant_religion = $request->get('applicant_religion');
        $applicationElementObject->co_applicant_profession_type = $request->get('co_applicant_profession');
        $applicationElementObject->profession_type = $request->get('profession');
        $applicationElementObject->product_name = $product_name;
        $applicationElementObject->co_applicant_designation = $request->get('co_applicant_designation');
        $applicationElementObject->co_applicant_for_signing = $request->has('co_applicant_for_signing') ? 1 : 2;
        $applicationElementObject->co_applicant_for_income = $request->has('co_applicant_for_income') ? 1 : 2;
        $applicationElementObject->duration = $request->get('duration_month') . '|' . $request->get('duration_year');
        $applicationElementObject->collection_advisor = $request->has('collection_advisor') && $request->get('collection_advisor') > 0 ? $request->get('collection_advisor') : 0;
        if ($initial_offer_id) {
            $applicationAdditionObject->initial_applied_tenure = $initial_offer_id;
        }else if(request()->has('initial_applied_tenure')){
            $applicationAdditionObject->initial_applied_tenure = $request->get('initial_applied_tenure');
        }

        $applicationAdditionObject->is_comm_no_linked_to_aadhar = $request->has('is_comm_no_linked_to_aadhar') ? $request->get('is_comm_no_linked_to_aadhar') : null;
        $applicationAdditionObject->aadhar_linked_mobile = $request->has('aadhar_linked_mobile') ? $request->get('aadhar_linked_mobile') : null;
        $applicationAdditionObject->coapp_is_comm_no_linked_to_aadhar = $request->has('coapp_is_comm_no_linked_to_aadhar') ? $request->get('coapp_is_comm_no_linked_to_aadhar') : null;
        $applicationAdditionObject->coapplicant_aadhar_linked_mobile = $request->has('coapplicant_aadhar_linked_mobile') ? $request->get('coapplicant_aadhar_linked_mobile') : null;
        $co_applicant_required_for_income_and_mandate = ($request->has('co_applicant_required_for_income_and_mandate')) ? 1 : 2;
        
        if (isset($applicationAdditionObject->co_applicant_required_for_mandate) && isset($applicationAdditionObject->id) && $co_applicant_required_for_income_and_mandate != $applicationAdditionObject->co_applicant_required_for_mandate) {
            $coapplicantsiging = new CoApplicateValidationLog();
            $coapplicantsiging->application_id = $id;
            $coapplicantsiging->user_id = Auth::user()->id;
            $coapplicantsiging->co_applicant_type = "Co applicant required for income and mandate";
            $coapplicantsiging->previous_tatus = $applicationAdditionObject->co_applicant_required_for_mandate;
            $coapplicantsiging->new_status = $co_applicant_required_for_income_and_mandate;
            $coapplicantsiging->save();

            if($co_applicant_required_for_income_and_mandate == 1){
                $name = isset($consumer_application->advisor->name) ? $consumer_application->advisor->name : '';
                $email = isset($consumer_application->advisor->email) ? $consumer_application->advisor->email : '';
                // $advisor_id = isset($consumer_application->advisor) && isset($consumer_application->advisor->id) ? $consumer_application->advisor->id : '';

                $comment = "@".$name." Co-applicant required for Income and Mandate set up";

                $markComment = (new GradeController(new Request()))->addComment($consumer_application->id, Auth::user()->id ?? 107, $comment);
                $id = $consumer_application->id;
                $message_body = "Dear ".$name."<br/><br/>
                    Co applicant required for income and mandate in application id ". $consumer_application->id ."<br/><br/>
                    Regards,<br/>
                    Credit Fair- Operations<br/>";

                if($email != ""){
                    Mail::send('emails.reminders.basic_reminder',
                        ['body' => $message_body]
                        , function ($message) use ($id, $email) {
                            $message->to($email)->subject($id.' - Co-applicant required for Income and Mandate set up');
                    });
                }
            }
        }

        $applicationAdditionObject->co_applicant_required_for_mandate = $co_applicant_required_for_income_and_mandate;

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

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

            $applicationElementObject->inverter_model_description =$request->has('model_description') ? $request->get('model_description') : null;
            // Skip overwriting values already set by Karza utility validation during electricity bill upload
            if (empty($electricityBillUpload) || !$this->utilityValidationSucceeded) {
                $applicationElementObject->inverter_monthly_power_bill =$request->get('monthly_power_bill');
                $applicationElementObject->discom_service_provider = $request->get('service_provider');
                if(strtolower($request->get('service_provider')) == "other"){
                    $applicationElementObject->other_discom_service_provider = $request->get('other_service_provider');
                }
            }
            $applicationElementObject->type_of_customer =$request->get('type_of_customer');
            $applicationElementObject->solar_power_type =$request->get('type_of_solar_power');
            $applicationElementObject->inverter_KW_installation =$request->get('KW_installation');
            $applicationElementObject->inverter_gross_project_amount =$request->get('gross_project_amount');
            $applicationElementObject->inverter_subsidy_amount =$request->get('subsidy_amount');
            $applicationElementObject->inverter_power_savings = $request->get('power_savings');
            // $applicationElementObject->discount_by_cf = $request->get('solar_discount_by_cf') ?? 0;
            $applicationElementObject->login_id_of_installer = $request->get('login_id_of_installer');
            $applicationElementObject->password = $request->get('installer_password');
        }

        if ($request->has('electricity_name_change')) {
            $applicationElementObject->electricity_name_change = $request->get('electricity_name_change');
        }

        if(Session::has('Edit_UTR_Number|-40')) {
            $applicationElementObject->reference_number = $request->has('reference_number') && $request->get('reference_number') ? $request->get('reference_number') : (!$request->has('reference_number') ? '' : ($applicationElementObject->reference_number ? $applicationElementObject->reference_number : ''));
        }else{
            $applicationElementObject->reference_number = $reference_number;
        }

        $newMerchantRiskMitigation = $this->calculateMerchantRiskMitigation($request->get('merchant_id'), $applicationElementObject, $consumer_application);
        if ($newMerchantRiskMitigation !== null) {
            $applicationElementObject->merchant_risk_mitigation = $newMerchantRiskMitigation;
        }
        $applicationElementObject->save();
        
        if ($request->has('gross_project_amount')) {
            $this->calculateInsurance(new \Illuminate\Http\Request([
                'id' => $id,
                'loan_amount' => $consumer_application->approved_amount,
                'discount' => $applicationElementObject->discount_by_cf ?? 0,
                'gross_project_amount' => $applicationElementObject->inverter_gross_project_amount
            ]));
        }

        $offerToUse = isset($merchantOffer) ? $merchantOffer : \App\MerchantOffers::find($request->has('offer_id') ? $request->get('offer_id') : $consumer_application->offer_id);
        if ($offerToUse && ($request->has('gross_project_amount') || $request->has('offer_id'))) {
            $consumer_application->application_element = $applicationElementObject;
            $ltv = (new GradeController(new Request()))->calculateLTV($consumer_application, $offerToUse);
            if (isset($applicationAdditionObject)) {
                $old_ltv = $applicationAdditionObject->loan_to_value_limit;
                
                $has_changed = false;
                $comment = "";
                
                $old_ltv = is_string($old_ltv) ? json_decode($old_ltv, true) : $old_ltv;
                if (
                    (!isset($old_ltv['ltv_gross_project_amount']) || round((float)$old_ltv['ltv_gross_project_amount'], 2) != round((float)$ltv['ltv_gross_project_amount'], 2)) ||
                    (!isset($old_ltv['ltv_net_loan_amount']) || round((float)$old_ltv['ltv_net_loan_amount'], 2) != round((float)$ltv['ltv_net_loan_amount'], 2))
                ) {
                    $has_changed = true;
                    $comment = "LTV Value Revised.<br>";
                    if (isset($old_ltv['ltv_gross_project_amount'])) {
                        $comment .= "Old LTV (Gross Project Amount): " . number_format((float)$old_ltv['ltv_gross_project_amount'], 2) . "%<br>";
                    }
                    if (isset($old_ltv['ltv_net_loan_amount'])) {
                        $comment .= "Old LTV (Net Loan Amount): " . number_format((float)$old_ltv['ltv_net_loan_amount'], 2) . "%<br>";
                    }
                }
                
                if ($has_changed) {
                    $comment .= "New LTV (Gross Project Amount): " . number_format((float)$ltv['ltv_gross_project_amount'], 2) . "%";
                    $comment .= "New LTV (Net Loan Amount): " . number_format((float)$ltv['ltv_net_loan_amount'], 2) . "%<br>";
                    $comment .= " Loan Amount: " . (isset($ltv['loan_amount']) ? $ltv['loan_amount'] : 0) . "";
                    $comment .= " Gross Project Amount: " . (isset($ltv['inverter_gross_project_amount']) ? $ltv['inverter_gross_project_amount'] : 0) . "<br>";
                    $comment .= " Net Loan Amount: " . (isset($ltv['net_loan_amount']) ? $ltv['net_loan_amount'] : 0);

                    $this->addComment($id, $comment);

                    ContentLogger::insert([
                        'application_id' => $id,
                        'data' => json_encode([
                            'ltv_gross_project_amount' => [
                                'old' => isset($old_ltv['ltv_gross_project_amount']) ? round((float)$old_ltv['ltv_gross_project_amount'], 2) : '',
                                'new' => round((float)$ltv['ltv_gross_project_amount'], 2)
                            ],
                            'ltv_net_loan_amount' => [
                                'old' => isset($old_ltv['ltv_net_loan_amount']) ? round((float)$old_ltv['ltv_net_loan_amount'], 2) : '',
                                'new' => round((float)$ltv['ltv_net_loan_amount'], 2)
                            ],
                        ]),
                        'status' => $consumer_application->state ?? '',
                        'created_at' => Carbon::now()->toDateTimeString(),
                        'user_id' => Auth::user() ? Auth::user()->id : 107,
                        'model' => 'consumer_application'
                    ]);
                }

                $applicationAdditionObject->loan_to_value_limit = [
                    'ltv_gross_project_amount' => $ltv['ltv_gross_project_amount'],
                    'ltv_net_loan_amount' => $ltv['ltv_net_loan_amount'],
                ];
            }
        }
        $applicationAdditionObject->save();

        $this->updatestatustonachregister($id);

        if($consumer_application->state == 'approved') {
            $homevilleController = (new HomevilleController(new Request(['id' => $id])))->updateLoanApplication();
            if($homevilleController) {
                $homevilleControllerResponse = $homevilleController->getData();
                if ($homevilleControllerResponse->status == 'FAIL') {
                    \Session::flash('error_homeville', 'HomeVille: ' . json_encode($homevilleControllerResponse->data));
                }
            }
        }

        if(isset($documentStatus['status']) && $documentStatus['status'] == 'FAIL' && $documentStatus['documents']){
            return redirect()->back()->withErrors(['File uploading failed, low quality image - '. implode(', ', $documentStatus['documents'])]);
        }

        \Session::flash('success', 'Application successfully Updated');

        $merchant = Merchant::where('id', $request->get('merchant_id'))->first(['table_of_offers']);
        $status_check = in_array($consumer_application->state, $this->statusBeforeDCD);
        if($foir_changed === "new" && $merchant->table_of_offers == 1 && $status_check){
            $cwFactory->logger(json_encode(['application_id' => $id, 'title' => 'calculate foir flow']));
            $this->checkAndCalculateFOIR($id, $consumer_application, $request, $isAmountChanged, $oldApprovedAmount);
        }
        if(strpos($request->path(),'bnpl-application')){
            return redirect()->to('admin/bnpl-applications');
        }

        $autoBRE = new autoBRE();
        // check data points and run bureau-BRE
        $cwFactory = new CloudWatchLoggerFactory();
        $cwFactory->logger(json_encode(['application_id' => $id, 'net_loan_amount' => $autoBRE->calculateNetLoanAmount($consumer_application->loan_amount, $merchantOffer), 'type_of_customer' => $applicationElementObject->type_of_customer, 'solar_power_type' => $applicationElementObject->solar_power_type]));
        
        $applicantTypesToCheck = [];
        if (isset($applicationElementObject->is_consent) && $applicationElementObject->is_consent == 1) {
            $applicantTypesToCheck[] = 1;
        }
        if (isset($applicationElementObject->is_co_app_consent) && $applicationElementObject->is_co_app_consent == 1) {
            $applicantTypesToCheck[] = 2;
        }

        foreach ($applicantTypesToCheck as $applicant_type) {
            if (in_array($application_status, ['in-process', 'incomplete form', 'form completed', 'waiting for documents']) && in_array($consumer_application->updated_by, ['admin', 'MERCHANT API', 'consumer_app', 'merchant admin panel', 'WhatsApp'])
                && $autoBRE->calculateNetLoanAmount($consumer_application->loan_amount, $merchantOffer) <= 500000 && isset($applicationElementObject->type_of_customer) && isset($applicationElementObject->solar_power_type)
                && $applicationElementObject->type_of_customer == 1 && $applicationElementObject->solar_power_type == 1) {
                if ($request->get('employee_status') != '' || $request->get('monthly_income') != '' || $request->get('power_savings') != '') {
                    $result = $autoBRE->checkDataPoints($id, $request);
                    if ($result) {
                        $merchant = DB::select('select m.id, m.is_auto_approve, m.is_auto_doc, m.pre_approval, m.grade_id from consumer_application c inner join merchant m on c.merchant_id = m.id where c.id = '.$id);
                        if(isset($merchant[0]->id) && ($merchant[0]->is_auto_approve || $merchant[0]->is_auto_doc || $merchant[0]->pre_approval) && $merchant[0]->grade_id) {
                            
                            $triggerAutoDecision = true;
                            if ($application_status == 'waiting for documents') {
                                $required_docs_record = ConsumerApplicationElement::where('application_id', $id)->first(['mandatory_document_list']);
                                if ($required_docs_record && !empty($required_docs_record->mandatory_document_list)) {
                                    $req_docs = explode(',', $required_docs_record->mandatory_document_list);
                                    $other_docs = array_diff($req_docs, ['consent_logs', 'co_app_consent_logs']);
                                    if (count($other_docs) > 0) {
                                        $triggerAutoDecision = false;
                                    }
                                }
                            }

                            if ($triggerAutoDecision) {
                                $jobId = QueueLog::where('application_id', $id)
                                    ->where('cmd', 'command:AutoDecision')
                                    ->where('input', 'like', '%"applicant_type":'.(int) $applicant_type.'%')
                                    ->value('job_id');
                                if(is_null($jobId)) {
                                    event(new EventAutoDecision(['id' => $consumer_application->id, 'applicant_type' => (int) $applicant_type]));
                                }
                            } else {
                                $this->generateSoftBureauReport($id, 'autoBRE', $applicant_type, false);
                                if ($applicant_type == 1) {
                                    $autoRejectResult = (new AutoRejection(new Request()))->autoReject(false, $id, 'bot');
                                    if ($autoRejectResult) {
                                        $consumer_application = ConsumerApplication::find($id);
                                        $consumer_application->state = "rejected";
                                        $consumer_application->save();
                                        StatusLogs::insert([
                                            'application_id' => $id,
                                            'user_id' => 107,
                                            'status' => 'rejected',
                                            'created_at' => Carbon::now()->toDateTimeString()
                                        ]);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        $lenderService = new LenderServices(new Request());
        if($co_app_added){
            $lenderService->sendConstantMessage($consumer_application->id,2);
        } else if (isset($co_app_mobile_changed) && $co_app_mobile_changed) {
            if (!isset($applicationElementObject->is_co_app_consent) || $applicationElementObject->is_co_app_consent != 1) {
                $lenderService->sendConstantMessage($consumer_application->id,2);
            }
        }

        if (isset($mobile_changed) && $mobile_changed) {
            if (!isset($applicationElementObject->is_consent) || $applicationElementObject->is_consent != 1) {
                $lenderService->sendConstantMessage($consumer_application->id,1);
            }
        }

        if ($actionType === 'save') {
            return redirect()->back()->with('success', 'Data saved successfully!');
        }else{
            return redirect()->to('admin/');
        }
    }

    public function checkAndCalculateFOIR($id, $consumer_application, $request, $isAmountChanged, $oldApprovedAmount) 
    {
        $emiCalculation = ApplicationEMICalculation::where('application_id', $id)->first(); 

        if ($emiCalculation && (in_array($emiCalculation->table_of_offers_logic, ['residual_emi', 'bureau_surrogate_limit', 'power_saving', 'banking_abb']))) {
            
            $isValidStatus = in_array($consumer_application->state, ['approved', 'cf approved']);

            if ($isValidStatus && $isAmountChanged) {
                $consumer_application->loadMissing(['emi', 'category', 'activeOffer']);
                $emiRequest = new Request();
                $emiRequest->replace([
                    'first_emi_date' => $consumer_application->emi->emi_date ?? null,
                    'loan_amount' => $request->get('approved_amount'),
                    'merchant_id' => $consumer_application->merchant_id,
                    'category_id' => $consumer_application->category->id ?? null,
                    'interest_type_id' => $consumer_application->activeOffer->interest_type_id ?? null,
                    'merchant_offer_id' => $request->get('offer_id') ?? $consumer_application->offer_id,
                    'user_id' => Auth::check() ? Auth::user()->id : 107
                ]);            

                $emiCalculation->residual_emi = null;
                $emiCalculation->table_of_offers_logic = null;
                $emiCalculation->save();

                $this->generateEMI($emiRequest, $consumer_application, $id);
                $username = isset(Auth::user()->name) ? Auth::user()->name : 'creditfair';
                $comment = "Approved amount reverted to Rs. ".$consumer_application->approved_amount."<br>
                            from the residual amount to Rs. ". $oldApprovedAmount ." <br>
                            changed by @".$username;

                $this->addComment($id, $comment);
            }
        } else {
            (new Slack(new Request([
                'title' => 'Auto Decision V1 - Started', 
                'fields' => ['id' => $id, 'time' => Carbon::now()->toDateTimeString()], 
                'group' => Slack::$STAGE_TESTING
            ])))->send();
            
            $grade = new GradeController(new Request());
            $approval = $grade->ApprovalCheckV1($id);
            
            (new Slack(new Request([
                'title' => 'Auto Decision V1 - Ended', 
                'fields' => ['id' => $id, 'time' => Carbon::now()->toDateTimeString()], 
                'group' => Slack::$STAGE_TESTING
            ])))->send();
        }
    }

    public function addComment($app_id, $comment){
        $username = isset(Auth::user()->name) ? Auth::user()->name : 'creditfair';
        Comments::insert([
            'application_id' => $app_id,
            'user_id' => isset(Auth::user()->id) ? Auth::user()->id : 107,
            'comment' => $comment,
            'show_consumer' => 0,
            'show_merchant' => 0,
            'created_at' => Carbon::now()->toDateTimeString(),
            'updated_at' => Carbon::now()->toDateTimeString(),
            'type' =>'consumer',
        ]);
    }

    private function detectAndResetKYC(Request $request, $currentApp, $id){
        // Reset Flags
        $karzaAppReset = false;
        $karzaCoAppReset = false;
        $digioAppReset = false;
        $digioCoAppReset = false;

        $digioAppChangedFields = [];
        $digioCoAppChangedFields = [];

        // Helper function to remove all spaces for comparison
        $stripSpaces = function ($val) {
            return str_replace(' ', '', $val ?? '');
        };

        // Fetch Element Data (needed for Father Name & Installation Addr)
        $elementCheck = ConsumerApplicationElement::select([
                    'father_name', 
                    'co_applicant_father_name',
                    'installation_address_landmark',
                    'installation_address_city',
                    'installation_address_state',
                    'installation_address_pincode',
                    'installation_address_line_1'
                ])->where('application_id', $id)->first();
                
        // ---------------------------------------------------------
        // 1. COMMON FIELDS (Affect both Applicant & Co-Applicant in some flows)
        // ---------------------------------------------------------

        // APPROVED AMOUNT: Affects both Digio Applicant and Co-Applicant
        if ($request->has('approved_amount') && $request->input('approved_amount') != $currentApp->approved_amount) {
            $digioAppReset = true;
            $digioCoAppReset = true;

            $digioAppChangedFields['approved_amount'] = [
                'old' => $currentApp->approved_amount,
                'new' => $request->input('approved_amount')
            ];

            $digioCoAppChangedFields['approved_amount'] = [
                'old' => $currentApp->approved_amount,
                'new' => $request->input('approved_amount')
            ];
        }


        if (!$digioAppReset && $elementCheck) {
            $instFields = ['installation_address_landmark', 'installation_address_city', 'installation_address_state', 'installation_address_pincode'];
            foreach ($instFields as $field) {
                if ($request->has($field)) {
                    // All installation fields are address fields, so we strip spaces for comparison
                    $reqVal = $stripSpaces($request->input($field));
                    $dbVal = $stripSpaces($elementCheck->$field);

                    if ($reqVal != $dbVal) {
                        $digioAppReset = true;
                        $digioAppChangedFields[$field] = [
                            'old' => $elementCheck->$field,
                            'new' => $request->input($field) // Keep original formatting for logs
                        ];
                        break;
                    }
                }
            }

            if (!$digioAppReset) {
                 $newInstAddr = ($request->has('installation_address_1') ? $request->get('installation_address_1') : "") . '' .
                               ($request->has('installation_address_2') ? $request->get('installation_address_2') : "") . '' .
                               ($request->has('installation_address_3') ? $request->get('installation_address_3') : "");

                if (($request->has('installation_address_1') || $request->has('installation_address_2'))) {
                    // Strip spaces for the concatenated line 1 check
                    if ($stripSpaces($newInstAddr) !== $stripSpaces($elementCheck->installation_address_line_1)) {
                        $digioAppReset = true;
                        $digioAppChangedFields['installation_address_line_1'] = [
                            'old' => $elementCheck->installation_address_line_1,
                            'new' => $newInstAddr
                        ];
                    }
                }
            }
        }

        // ---------------------------------------------------------
        // 2. APPLICANT SPECIFIC CHECKS (Type 1)
        // ---------------------------------------------------------

        $newApplicantName = $this->getFullName($request);
        if ($newApplicantName && $newApplicantName !== $currentApp->name) {
            $karzaAppReset = true;
        }

        // KARZA APPLICANT FIELDS
        if (!$karzaAppReset) {
            $karzaAppFields = [
                'dob', 'gender',
                'current_address_line_1', 'current_address_state', 'current_address_city',
                'current_address_pincode', 'current_address_landmark',
                'permanent_address_line_1', 'permanent_address_state', 'permanent_address_city',
                'permanent_address_pincode', 'permanent_address_landmark'
            ];
            foreach ($karzaAppFields as $field) {
                if ($request->has($field)) {
                    $reqVal = $request->input($field);
                    $dbVal = $currentApp->$field;

                    // Apply space stripping only if it's an address field
                    if (strpos($field, 'address') !== false) {
                        $reqVal = $stripSpaces($reqVal);
                        $dbVal = $stripSpaces($dbVal);
                    }

                    if ($reqVal != $dbVal) {
                        $karzaAppReset = true;
                        break;
                    }
                }
            }
        }

        // KARZA APPLICANT ELEMENT (Father Name)
        if (!$karzaAppReset && $elementCheck) {
            if ($request->has('father_name') && $request->input('father_name') != $elementCheck->father_name) {
                $karzaAppReset = true;
            }
        }

        // DIGIO APPLICANT FIELDS
        if (!$digioAppReset) {
            $digioAppFields = [
                'email',
                'current_address_line_1', 'current_address_city',
                'current_address_pincode', 'current_address_landmark',
                'current_address_status'
            ];
            foreach ($digioAppFields as $field) {
                if ($request->has($field)) {
                    $reqVal = $request->input($field);
                    $dbVal = $currentApp->$field;

                    // Apply space stripping only if it's an address field
                    if (strpos($field, 'address') !== false) {
                        $reqVal = $stripSpaces($reqVal);
                        $dbVal = $stripSpaces($dbVal);
                    }

                    if ($reqVal != $dbVal) {
                        $digioAppReset = true;
                        $digioAppChangedFields[$field] = [
                            'old' => $currentApp->$field,
                            'new' => $request->input($field)
                        ];
                        break;
                    }
                }
            }
        }
        
        // DIGIO APPLICANT ELEMENT (Father Name)
        if (!$digioAppReset && $elementCheck) {
            if ($request->has('father_name') && $request->input('father_name') != $elementCheck->father_name) {
                $digioAppReset = true;
                $digioAppChangedFields['father_name'] = [
                    'old' => $elementCheck->father_name,
                    'new' => $request->input('father_name')
                ];
            }
        }

        // ---------------------------------------------------------
        // 3. CO-APPLICANT SPECIFIC CHECKS (Type 2)
        // ---------------------------------------------------------

        // NAME Check
        if ($request->has('co_applicant_name') && $request->input('co_applicant_name') != $currentApp->co_applicant_name) {
            $karzaCoAppReset = true;
        }

        // KARZA CO-APPLICANT FIELDS
        if (!$karzaCoAppReset) {
            $karzaCoAppFields = [
                'co_applicant_dob', 'co_applicant_gender',
                'co_applicant_address_line_1', 'co_applicant_address_state',
                'co_applicant_address_pincode', 'co_applicant_address_city',
                'co_applicant_address_landmark'
            ];
            foreach ($karzaCoAppFields as $field) {
                if ($request->has($field)) {
                    $reqVal = $request->input($field);
                    $dbVal = $currentApp->$field;

                    // Apply space stripping only if it's an address field
                    if (strpos($field, 'address') !== false) {
                        $reqVal = $stripSpaces($reqVal);
                        $dbVal = $stripSpaces($dbVal);
                    }

                    if ($reqVal != $dbVal) {
                        $karzaCoAppReset = true;
                        break;
                    }
                }
            }
        }
        // KARZA CO-APPLICANT ELEMENT (Father Name)
        if (!$karzaCoAppReset && $elementCheck) {
            if ($request->has('co_applicant_father_name') && $request->input('co_applicant_father_name') != $elementCheck->co_applicant_father_name) {
                $karzaCoAppReset = true;
            }
        }

        // DIGIO CO-APPLICANT FIELDS
        if (!$digioCoAppReset) {
            if ($request->has('co_applicant_email') && $request->input('co_applicant_email') != $currentApp->co_applicant_email) {
                $digioCoAppReset = true;
                $digioCoAppChangedFields['co_applicant_email'] = [
                    'old' => $currentApp->co_applicant_email,
                    'new' => $request->input('co_applicant_email')
                ];
            }
        }
        // DIGIO CO-APPLICANT ELEMENT (Father Name)
        if (!$digioCoAppReset && $elementCheck) {
            if ($request->has('co_applicant_father_name') && $request->input('co_applicant_father_name') != $elementCheck->co_applicant_father_name) {
                $digioCoAppReset = true;
                $digioCoAppChangedFields['co_applicant_father_name'] = [
                    'old' => $elementCheck->co_applicant_father_name,
                    'new' => $request->input('co_applicant_father_name')
                ];
            }
        }

        // ---------------------------------------------------------
        // 4. EXECUTE DELETION
        // ---------------------------------------------------------
        if ($karzaAppReset || $karzaCoAppReset || $digioAppReset || $digioCoAppReset) {

            $logPayload = [
                "application_id" => $id,
                "title" => "detectAndResetKYC",
                "flags" => [
                    "karzaAppReset"   => $karzaAppReset,
                    "karzaCoAppReset" => $karzaCoAppReset,
                    "digioAppReset"   => $digioAppReset,
                    "digioCoAppReset" => $digioCoAppReset
                ],
                "digioApplicantChanges"   => $digioAppReset ? $digioAppChangedFields : [],
                "digioCoApplicantChanges" => $digioCoAppReset ? $digioCoAppChangedFields : []
            ];

            $cwFactory = new CloudWatchLoggerFactory();
            $cwFactory->logger(json_encode($logPayload));
            $this->performKYCSoftDelete($id, $karzaAppReset, $karzaCoAppReset, $digioAppReset, $digioCoAppReset);
        }
    }

    private function performKYCSoftDelete($applicationId, $karzaApp, $karzaCoApp, $digioApp, $digioCoApp){
        // --- KARZA DELETION LOGIC ---
        if ($karzaApp && !self::checkKarzaApproved($applicationId, 1)) {
            KarzaVideoAttribute::where('application_id', $applicationId)
                ->where('applicant_type', 1)
                ->whereNull('deleted_at')
                ->delete();
        }
        if ($karzaCoApp && !self::checkKarzaApproved($applicationId, 2)) {
            KarzaVideoAttribute::where('application_id', $applicationId)
                ->where('applicant_type', 2)
                ->whereNull('deleted_at')
                ->delete();
        }
        if ($digioApp){
            DigioVKYC::where('application_id', $applicationId)
                ->whereNull('deleted_at')
                ->where(function ($query) {
                    $query->where('kyc_status', '!=', 'approved')
                        ->orWhereNull('kyc_status');
                })
                ->where('applicant_type', 1)
                ->delete();
        }
        if ($digioCoApp) {
            DigioVKYC::where('application_id', $applicationId)
                ->whereNull('deleted_at')
                ->where(function ($query) {
                    $query->where('kyc_status', '!=', 'approved')
                        ->orWhereNull('kyc_status');
                })
                ->where('applicant_type', 2)
                ->delete();
        }
    }

    public function updateProformaAttributes($id, Request $request){
        $merchantInsuranceConfig = (new AccountingController())->getMerchantInsuranceConfig($id);
        $proFormDataUpdate = [];
        $proFormDataUpdate['insurance_premium_by_merchant'] = $merchantInsuranceConfig['insurance_premium_by_merchant'];
        $proFormDataUpdate['insurance_premium_applicable'] = $merchantInsuranceConfig['insurance_premium_applicable'];
        $proFormDataUpdate['processing_fee_by_merchant'] = $merchantInsuranceConfig['processing_fee_by_merchant'];
        if($request->get('insurance_collection_method') >= 0 && ($request->has('source') && $request->get('source') != 'whatsapp_agent')){
            $proFormDataUpdate['insurance_premium_by_merchant'] = !is_null($request->get('insurance_collection_method')) ? $request->get('insurance_collection_method') : 0;
        }

        $proFormaInvoice = ProFormaInvoice::where('application_id', $id)->first(['id']);

        if(isset($proFormaInvoice->id)){
            if($request->get('spouse_name')){
                $proFormDataUpdate['spouse_name'] = $request->get('spouse_name');
            }
            if(!$request->has('insurance_collection_method')){
                unset($proFormDataUpdate['insurance_premium_by_merchant']);
            }
            ProFormaInvoice::where('id', $proFormaInvoice->id)->update($proFormDataUpdate);
        }else{
            $proFormaInvoice = new ProFormaInvoice();
            $proFormaInvoice->application_id = $id;
            if($request->get('spouse_name')) {
                $proFormaInvoice->spouse_name = $request->get('spouse_name');
            }
            $proFormaInvoice->insurance_premium_by_merchant = $proFormDataUpdate['insurance_premium_by_merchant'];
            $proFormaInvoice->insurance_premium_applicable = $proFormDataUpdate['insurance_premium_applicable'];
            $proFormaInvoice->insurance_coverage = $merchantInsuranceConfig['insurance_coverage'];
            $proFormaInvoice->processing_fee_by_merchant = $merchantInsuranceConfig['processing_fee_by_merchant'];
            $proFormaInvoice->save();
        }
    }

    public function updateAvanseCIF($id, $consumer_application, Request $request){
        if($request->has('cif_number') && $request->get('cif_number')){
            $avanseCustomer = AvanseCreateCustomer::where('application_id', $id)->where('applicant_id', $consumer_application->applicant_id)->first(['cif']);
            if(!isset($avanseCustomer->cif)) {
                AvanseCreateCustomer::insert(
                    [
                        'application_id' => $id,
                        'applicant_id' => $consumer_application->applicant_id,
                        'cif' => $request->get('cif_number'),
                        'primaryRelationOfficer' => 0,
                        'dedupReq' => 0,
                        'created_at' => Carbon::now()->toDateTimeString(),
                        'user_id' => Auth::check() ? Auth::user()->id : 107,
                    ]
                );
            }
        }
        if($request->has('co_cif_number') && $request->get('co_cif_number')){
            $avanseCustomer = AvanseCreateCustomer::where('application_id', $id)->where('applicant_id', $consumer_application->co_applicant_id)->first(['cif']);
            if(!isset($avanseCustomer->cif)) {
                AvanseCreateCustomer::insert(
                    [
                        'application_id' => $id,
                        'applicant_id' => $consumer_application->co_applicant_id,
                        'cif' => $request->get('co_cif_number'),
                        'primaryRelationOfficer' => 0,
                        'dedupReq' => 0,
                        'created_at' => Carbon::now()->toDateTimeString(),
                        'user_id' => Auth::check() ? Auth::user()->id : 107,
                    ]
                );
            }
        }
    }

    public function saveUserGeolocation($application, $data)
    {
        if ($data['latitude'] && $data['longitude']) {
            $userGeolocation = UserGeolocation::where('_id', $application->id)->where('applicant_type', $data['applicant_type'])->where('id_type', $data['id_type'])
                ->where('service', $data['service'])->whereNull('deleted_at')->first();

            if (isset($data['pincode']) && !$data['pincode']) {
                $data['pincode'] = $this->getPincodeData($data);
            }

            if (!isset($userGeolocation->id) || $data['service'] == 'esign') {
                if($data['latitude'] != 41.90344940 && $data['longitude'] != -87.67884210) {
                    UserGeolocation::insert([
                        '_id' => isset($data['_id']) ? $data['_id'] : $application->id,
                        'id_type' => $data['id_type'],
                        'applicant_id' => isset($data['applicant_id']) ? $data['applicant_id'] : (isset($application->applicant_id) ? $application->applicant_id : 0),
                        'applicant_type' => $data['applicant_type'],
                        'service' => $data['service'],
                        'latitude' => $data['latitude'],
                        'longitude' => $data['longitude'],
                        'pincode' => isset($data['pincode']) ? (isset($data['pincode'][0]) ? $data['pincode'][0] : $data['pincode']) : '',
                        'created_at' => Carbon::now()->toDateTimeString()
                    ]);
                }
            } else {
                UserGeolocation::where('id', $userGeolocation->id)->update(['latitude' => $data['latitude'], 'longitude' => $data['longitude'], 'pincode' => isset($data['pincode']) ? $data['pincode'] : '']);
            }
        }
    }

    public function updateSanctionAmount($id, $consumer_application, Request $request){
        $condition = false;
        if($consumer_application->approved_amount != $request->get('approved_amount')){
            $condition = true;
        }

        if(!$condition){
            $sanctionLogs = SanctionAmountLogs::where('application_id', $id)->orderBy('created_at', 'desc')->first(['approved_amount']);
            if (!isset($sanctionLogs->approved_amount)){
                $condition = true;
            }
        }

        if($condition) {
            $sanctionLogs = $sanctionLogs ?? SanctionAmountLogs::where('application_id', $id)->orderBy('created_at', 'desc')->first(['approved_amount']);
            if (!isset($sanctionLogs->approved_amount) || (isset($sanctionLogs->approved_amount) && $sanctionLogs->approved_amount != $request->get('approved_amount'))) {


                $isSigned = ConsumerApplicationFiles::where('consumer_application_id', $id)->where('file_type', 'loan_agreement_esign')->first(['id']);

                if(isset($isSigned->id)) {
                    $sanctionLogs = new SanctionAmountLogs();
                    $sanctionLogs->application_id = $id;
                    $sanctionLogs->user_id = Auth::user()->id;
                    $sanctionLogs->approved_amount = $consumer_application->approved_amount;
                    $sanctionLogs->save();
                }
            }
        }
    }

    public function checkCoAppRequireApi($application_id){
        $check =  $this->checkCoAppRequire($application_id, Input::get('status'));
        return \response()->json(['status' => 'OK', 'co_app_required' => $check]);

    }

    public function checkCoAppRequire($applicationId, $status = '')
    {
        $consumerApplication = ConsumerApplication::find($applicationId, ['loan_amount', 'co_applicant_name', 'offer_id']);
        $element = ConsumerApplicationElement::where('application_id', $applicationId)
            ->first(['type_of_customer_application']);

        $nonIndividual = $element->type_of_customer_application === 'Non-individual';

        if ($status === 'in-process' && $nonIndividual) {
            return false;
        }

        $merchantOffer = MerchantOffers::find($consumerApplication->offer_id, ['tenure', 'advance_type', 'advance_emi']);
        $netLoanAmount = (new autoBRE())->calculateNetLoanAmount($consumerApplication->loan_amount, $merchantOffer);

        if ($netLoanAmount < 500000 || isset($consumerApplication->co_applicant_name)) {
            return false;
        }

        return !$nonIndividual;
    }


    public function markCommentForCoApp($application_id){
        if($this->checkCoAppRequire($application_id)){
        $consumer_application = ConsumerApplication::where('id', $application_id)->select('created_by')->first();
        $comment = "";

        if(isset($consumer_application->created_by)){
            $user = User::where('id', $consumer_application->created_by)->first(['name']);
            $comment ='@'.$consumer_application->created_by.'-'.$user->name;
        }
        $comment = $comment." Co-applicant required, Net loan Amount > 5 Lakhs";

        $markComment = (new GradeController(new Request()))->addComment($application_id,107,$comment);}
        return;
    }

    public function updatestatustonachregister($id)
    {
        $status_array = ['disbursed'];
        $application = ConsumerApplication::with('monthlymandate', 'fullmandate');
        $applications = $application->where('id', $id)->whereNull('is_deleted')->whereIn('consumer_application.state', $status_array)->groupBy('id')->get(['id', 'name', 'email', 'mobile_number', 'merchant_id', 'lender_id', 'state']);

        foreach ($applications as $application) {
            if (isset($application->monthlymandate->umrn) && !empty($application->monthlymandate->umrn) && $application->monthlymandate->umrn != "0") {
                if (isset($application->monthlymandate->mode) && $application->monthlymandate->status == 'active') {
                    ConsumerApplication::where('id', $id)->update(['state' => 'nach registered']);
                    StatusLogs::insert([
                        'application_id' => $id,
                        'user_id' => 107,
                        'status' => 'nach registered',
                        'created_at' => Carbon::now()->toDateTimeString()
                    ]);
                }
            } elseif (isset($application->fullmandate->umrn) && !empty($application->fullmandate->umrn) && $application->fullmandate->umrn != "0") {
                if (isset($application->fullmandate->mode) && $application->fullmandate->status == 'active') {
                    ConsumerApplication::where('id', $id)->update(['state' => 'nach registered']);
                    StatusLogs::insert([
                        'application_id' => $id,
                        'user_id' => 107,
                        'status' => 'nach registered',
                        'created_at' => Carbon::now()->toDateTimeString()
                    ]);
                }
            }

            $payloads[] = [
                'payload' => json_encode(["id" => $id, "status" => "nach registered", "previous_status" => "disbursed", "auth_user_id" => 107]),
                'from' => 'statusChange',
                'application_id' => $id,
                'available_at' => Carbon::now()->toDateTimeString(),
                'created_at' => Carbon::now()->toDateTimeString(),
                'is_available' => 1
            ];
            JobProvider::insert($payloads);
        }
    }

    public function generateEMIIFRequired(Request $request, $application, $id)
    {
        $emiCalculation = ApplicationEMICalculation::where('application_id', $id)
            ->first(['id', 'emi_date', 'offer_id']);
        if (isset($emiCalculation->id)) {
            if ($this->checkForEMIGenerateDatapoints($request, $application, $id, $emiCalculation)) {
                $offer = MerchantOffers::where('id', $request->get('offer_id'))->first(['interest_type_id', 'id']);

                if($offer) {
                    $data =
                        [
                            'first_emi_date' => date('d/m/Y', strtotime($emiCalculation->emi_date)),
                            'loan_amount' => $request->get('approved_amount'),
                            'merchant_id' => $request->get('merchant_id'),
                            'category_id' => $request->get('purpose'),
                            'interest_type_id' => $offer->interest_type_id,
                            'merchant_offer_id' => $offer->id
                        ];
                    $request = new Request();
                    $request->request->add(
                        $data
                    );
                    $this->generateEMI($request, $application, $id);
                }
            }
        }
    }

    /**
     * Tells whether any data point the EMI schedule is derived from changed in this request,
     * i.e. whether the schedule has to be regenerated.
     */
    public function checkForEMIGenerateDatapoints(Request $request, $application, $id, $emiCalculation = null)
    {
        if ($emiCalculation !== null && $emiCalculation->offer_id != $request->get('offer_id')) {
            return true;
        }

        // Cast to array so a missing pro forma / element row simply yields null values.
        $saved = (array) DB::selectOne(
            'SELECT pf.insurance_premium_by_merchant, cae.inverter_gross_project_amount, cae.solar_power_type
               FROM consumer_application ca
               LEFT JOIN pro_forma_invoice pf ON pf.application_id = ca.id
               LEFT JOIN consumer_application_element cae ON cae.application_id = ca.id
              WHERE ca.id = ?',
            [$id]
        );

        // request key => currently saved value
        $datapoints = [
            'approved_amount' => $application->approved_amount,
            'offer_id' => $application->offer_id,
            'merchant_id' => $application->merchant_id,
            'insurance_collection_method' => array_get($saved, 'insurance_premium_by_merchant'),
            'gross_project_amount' => array_get($saved, 'inverter_gross_project_amount'),
            'type_of_solar_power' => array_get($saved, 'solar_power_type'),
        ];

        foreach ($datapoints as $requestKey => $savedValue) {
            if ($savedValue != $request->get($requestKey)) {
                return true;
            }
        }

        return false;
    }

    public function setMandate($request, $id)
    {

        $emis = ApplicationEMICalculation::where('application_id', $id)->first(['emi']);
        $mandate_amount = $request->get('mandate_amount');
        if (isset($emis->emi)) {
            if ($emis->emi != $request->get('mandate_amount')) {
                $mandate_amount = $emis->emi;
            }
        }
        $_mandate_amount = $request->get('_mandate_amount');
        if ($request->get('approved_amount') != $request->get('_mandate_amount')) {
            $_mandate_amount = $request->get('approved_amount');
        }

        $nachSetups = [
            [
                'action' => $request->get('action'),
                'collection' => $request->get('collection'),
                'frequency' => $request->get('frequency'),
                'mandate_amount' => $mandate_amount,
                'monthly_frequency' => 0,
                'umrn' => $request->get('umrn'),
                'mode' => $request->get('mode'),
            ],
            [
                'action' => $request->get('_action'),
                'collection' => $request->get('_collection'),
                'frequency' => $request->get('_frequency'),
                'mandate_amount' => $_mandate_amount,
                'monthly_frequency' => 1,
                'umrn' => $request->get('_umrn'),
                'mode' => $request->get('_mode'),

            ]
        ];

        foreach ($nachSetups as $nachSetup) {
            $mandate = Mandate::where('consumer_application_id', $id)->where('monthly_frequency', $nachSetup['monthly_frequency'])->orderBy('created_at', 'desc')->first(['id']);
            if (!isset($mandate->id)) {
                $nachSetup = array_merge($nachSetup, ['consumer_application_id' => $id, 'created_at' => Carbon::now()->toDateTimeString(), 'status' => 1]);
                Mandate::insert($nachSetup);
            } else {
                $nachSetup = array_merge($nachSetup, ['updated_at' => Carbon::now()->toDateTimeString()]);
                Mandate::where('consumer_application_id', $id)->where('monthly_frequency', $nachSetup['monthly_frequency'])->update($nachSetup);
            }
        }
    }

    public function exotelService($service_type, Request $request)
    {
        if ($service_type == 'call') {
            $exotel = new ExotelServices($request);
            return $exotel->call();
        }

        return \response()->json(['status' => 'FAIL', 'message' => 'Can\'t connect to service']);
    }

    public function applicationDestroy($id)
    {
        $application = ConsumerApplication::find($id);
        $advisor_id = isset($application->advisor) && isset($application->advisor->id) ? $application->advisor->id : '';
        $slack_url = isset($application->advisor) && isset($application->advisor->slack_url) ? $application->advisor->slack_url : '';
        $segment = User::where('id', $advisor_id)->first(['id', 'name', 'slack_id']);
        if(isset($segment->slack_id) && $segment->slack_id) {
            (new Slack(new Request(['title' => 'Application Deleted', 'fields' => ['Deleted By' => Auth::user()->name, 'Customer Name' => $application->name, 'application_id' => $id], 'group' => 'loan_application','tagging' => [$advisor_id]])))->send();
            (new Slack(new Request(['title' => 'Application Deleted', 'fields' => ['Deleted By' => Auth::user()->name, 'Customer Name' => $application->name, 'application_id' => $id], 'group' => $slack_url])))->send();
        }
        if ($application) {
            StatusLogs::insert([
                'application_id' => $id,
                'user_id' => Auth::user()->id,
                'status' => 'deleted',
                'reason' => '',
                'created_at' => Carbon::now()->toDateTimeString()
            ]);

            ConsumerApplication::where('id', $id)->update(['is_deleted' => 1]);
            \Session::flash('success', 'Application successfully deleted');
            return redirect()->back();
        } else {
            \Session::flash('error', 'Application not deleted');
            return redirect()->back();
        }
    }

    public function paymentDestroy($id)
    {
        $application = 0;
        $paymentdata = PaymentTransaction::where('cf_transaction_id', $id)->whereNull('is_deleted_at')->get();
        if ($paymentdata) {
            foreach ($paymentdata as $transaction) {
                if (isset($transaction->emi_payment_id) && !empty($transaction->emi_payment_id)) {
                    $payments = EmiPayment::with('transaction')->where('id', $transaction->emi_payment_id)->first();
                    $application = $payments->application_id;
                    if ($payments) {
                        //if ($payments->status != "success") {
                        $amount_payable = ($payments->emi_amount + $payments->bounce_charges + $payments->delay_penalty) - $payments->charges_waived;
                        $amount_received = 0;
                        if ($payments->transaction) {
                            foreach ($payments->transaction as $paymenttransaction) {
                                if ($paymenttransaction->status != "rejected" && $paymenttransaction->id != $transaction->id) {
                                    $amount_received = $amount_received + $paymenttransaction->amount;
                                }
                            }
                        }
                        if ($amount_received == 0) {
                            EmiPayment::where('id', $payments->id)->update(['payment_status' => 'pending']);
                        } elseif ($amount_payable > $amount_received) {
                            EmiPayment::where('id', $payments->id)->update(['payment_status' => 'partial']);
                        }

                        //}
                    }
                    PaymentTransaction::where('id', $transaction->id)->update(['is_deleted_at' => Carbon::now()->toDateTimeString(), 'deleted_by' => Auth::user()->id]);
                }

            }
            if ($application != 0) {
                $rps_exist = RPS_Logs::where('application_id', (int)$application)->where('bpi_interest','>',0)->exists();
                if(!$rps_exist) {
                    $loan_managent = new LoanManagement();
                    //$loan_managent = new PaymentEmi();
                    $loan_managent->paymentCalculate($application);
                }
            }
            \Session::flash('success', 'Payment successfully deleted');
            return redirect()->back();
        } else {
            \Session::flash('error', 'Payment not deleted');
            return redirect()->back();
        }
    }

    public function refundPayment(Request  $request){
        $payment = PaymentTransaction::where('id', $request->get('id'))->first();
        if(isset($payment->id)) {

            $bank = Bank::where('application_id', $payment->application_id)->where('applicant_type', 1)->first();

            if(!isset($bank->id)){
                return response()->json(['message' => 'Customer Bank details is missing', 'status' => 'FAIL'], 200);
            }

            PaymentTransaction::where('id', $request->get('id'))
                ->update(['refund_maker_at' => date('Y-m-d H:i:s'), 'refund_maker_id' => Auth::user()->id]);

            $data = [
                'id' => $payment->application_id,
                'amount' => $payment->amount,
                'bank' => $bank->bank_name,
                'account_type' => $bank->account_type,
                'name' => $bank->name,
                'branch_name' => $bank->branch_name,
                'account_number' => $bank->account_number,
                'ifsc_code' => $bank->ifsc_code
            ];

            $this->sendRefundEmail($data);
            return response()->json(['message' => 'Refund initiated successfully', 'status' => 'OK'], 200);
        }else{
            return response()->json(['centers' => 'Failed to initiated refund', 'status' => 'FAIL'], 200);
        }
    }

    function sendRefundEmail($data){
        \Mail::send('emails.reminders.basic_reminder',
            ['body' => view('emails.refund_payment', ['data' => $data])]
            , function ($message) use ($data){
                $message->to('accounts@creditfair.in')->subject('Refund initiated - '. $data['name']);
                $message->cc(['collections@creditfair.in']);
            });
    }

    public function paymentRefund($id)
    {
        $application = 0;
        $paymentdata = PaymentTransaction::where('cf_transaction_id', $id)->whereNull('is_deleted_at')->get();
        if ($paymentdata) {
            foreach ($paymentdata as $transaction) {
                PaymentTransaction::where('id', $transaction->id)
                    ->update(['refunded_at' => date('Y-m-d H:i:s'), 'refunded_by' => Auth::user()->id]);
                // $emi_amount = $transaction->amount;
                $application = $transaction->application_id;
            }
            if ($application != 0) {
                $loan_managent = new LoanManagement();
                $loan_managent->paymentCalculate($application);
            }
            // $bankDetails = Bank::where('application_id',$application)->orderBy('created_at','desc')->first();
            // // send mail for refund info
            // $message = "Hey team,<br>
            //     New refund is requested for application. Please refer below table and check bank details for the same
            //     <br><br>
            //     <table style='border: 1px solid;
            //     border-collapse: collapse; text-align: center'>
            //         <tr>
            //             <th style='border: 1px solid;
            //             border-collapse: collapse'>App id</th>
            //             <th style='border: 1px solid;
            //             border-collapse: collapse'>Name</th>
            //             <th style='border: 1px solid;
            //             border-collapse: collapse'>Account Type</th>
            //             <th style='border: 1px solid;
            //             border-collapse: collapse'>Bank</th>
            //             <th style='border: 1px solid;
            //             border-collapse: collapse'>Branch</th>
            //             <th style='border: 1px solid;
            //             border-collapse: collapse'>Account No</th>
            //             <th style='border: 1px solid;
            //             border-collapse: collapse'>IFSC Code</th>
            //             <th style='border: 1px solid;
            //             border-collapse: collapse'>EMI Amount</th>
            //         </tr>
            //         <tr>
            //             <td style='border: 1px solid;
            //     border-collapse: collapse'>$bankDetails->application_id</td>
            //             <td style='border: 1px solid;
            //     border-collapse: collapse'>$bankDetails->name</td>
            //             <td style='border: 1px solid;
            //     border-collapse: collapse'>$bankDetails->account_type</td>
            //             <td style='border: 1px solid;
            //     border-collapse: collapse'>$bankDetails->bank_name</td>
            //             <td style='border: 1px solid;
            //     border-collapse: collapse'>$bankDetails->branch_name</td>
            //             <td style='border: 1px solid;
            //     border-collapse: collapse'>$bankDetails->account_number</td>
            //             <td style='border: 1px solid;
            //     border-collapse: collapse'>$bankDetails->ifsc_code</td>
            //             <td style='border: 1px solid;
            //     border-collapse: collapse'>₹$emi_amount</td>
            //         </tr>
            //     </table>
            // ";
            // $email =  _env('APP_CONNECTION') ? ['accounts@creditfair.in'] : [Auth::user()->email];
            // Mail::send('emails.reminders.basic_reminder',
            //     ['body'=> $message]
            //     , function ($message) use ($email) {
            //         $message->to($email);
            //         $message->cc('collections@creditfair.in');
            //         $message->subject('New payment refund request');
            //     });

            \Session::flash('success', 'Payment successfully Refunded');
            return redirect()->back();
        } else {
            \Session::flash('error', 'Payment not Refunded');
            return redirect()->back();
        }
    }


    public function getCenterFromMerchant($id)
    {
        $centers = MerchantLocation::where('merchant_id', $id)
            ->get();

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

    public function getCentersFromMultiMerchants(Request $request)
    {
        $_merchant_id = (null != $request->get('_merchant_id')) ? $request->get('_merchant_id'): [];
        $centers = MerchantLocation::whereNull('deleted_at')->whereIn('merchant_id', $_merchant_id)->get();
        return response()->json(['centers' => $centers, 'status' => 'OK'], 200);
    }

    public function copyFilesData()
    {
        $file_income_proofs = ConsumerApplication::whereNotNull('file_income_proof')->pluck('file_income_proof', 'id');
        foreach ($file_income_proofs as $application_id => $file_name) {
            if (ConsumerApplicationFiles::where('consumer_application_id', $application_id)->where('file_type', 'file_income_proof')->first()) continue;
            $consumerApplicationFiles = new ConsumerApplicationFiles();
            $consumerApplicationFiles->consumer_application_id = $application_id;
            $consumerApplicationFiles->file_type = "file_income_proof";
            $consumerApplicationFiles->file_path = $file_name;
            $consumerApplicationFiles->save();
        }

        $file_bank_statements = ConsumerApplication::whereNotNull('file_bank_statement')->pluck('file_bank_statement', 'id');
        foreach ($file_bank_statements as $application_id => $file_name) {
            if (ConsumerApplicationFiles::where('consumer_application_id', $application_id)->where('file_type', 'file_bank_statement')->first()) continue;
            $consumerApplicationFiles = new ConsumerApplicationFiles();
            $consumerApplicationFiles->consumer_application_id = $application_id;
            $consumerApplicationFiles->file_type = "file_bank_statement";
            $consumerApplicationFiles->file_path = $file_name;
            $consumerApplicationFiles->save();
        }

        $file_pan_cards = ConsumerApplication::whereNotNull('file_pan_card')->pluck('file_pan_card', 'id');
        foreach ($file_pan_cards as $application_id => $file_name) {
            if (ConsumerApplicationFiles::where('consumer_application_id', $application_id)->where('file_type', 'file_pan_card')->first()) continue;
            $consumerApplicationFiles = new ConsumerApplicationFiles();
            $consumerApplicationFiles->consumer_application_id = $application_id;
            $consumerApplicationFiles->file_type = "file_pan_card";
            $consumerApplicationFiles->file_path = $file_name;
            $consumerApplicationFiles->save();
        }

        $file_aadhaar_cards = ConsumerApplication::whereNotNull('file_aadhaar_card')->pluck('file_aadhaar_card', 'id');
        foreach ($file_aadhaar_cards as $application_id => $file_name) {
            if (ConsumerApplicationFiles::where('consumer_application_id', $application_id)->where('file_type', 'file_aadhaar_card')->first()) continue;
            $consumerApplicationFiles = new ConsumerApplicationFiles();
            $consumerApplicationFiles->consumer_application_id = $application_id;
            $consumerApplicationFiles->file_type = "file_aadhaar_card";
            $consumerApplicationFiles->file_path = $file_name;
            $consumerApplicationFiles->save();
        }

        $file_electricity_bills = ConsumerApplication::whereNotNull('file_electricity_bill')->pluck('file_electricity_bill', 'id');
        foreach ($file_electricity_bills as $application_id => $file_name) {
            if (ConsumerApplicationFiles::where('consumer_application_id', $application_id)->where('file_type', 'file_electricity_bill')->first()) continue;
            $consumerApplicationFiles = new ConsumerApplicationFiles();
            $consumerApplicationFiles->consumer_application_id = $application_id;
            $consumerApplicationFiles->file_type = "file_electricity_bill";
            $consumerApplicationFiles->file_path = $file_name;
            $consumerApplicationFiles->save();
        }

        die("Migration done successfully !");
    }

    public function getResults(Request $request)
    {
        $dashboard_filter = ($request->has('filter') && !empty($request->get('filter'))) ? $request->get('filter') : "";
        if ($dashboard_filter != "") {
            $dashboard_filter_array = json_decode(base64_decode($dashboard_filter));
        }
        $keyword = $request->input('search_text');
        $data['status'] = $request->has('status') ? $request->get('status') : '';

        $data['from_date'] = ($request->has('from_date') && !empty($request->get('from_date'))) ? Carbon::createFromFormat('Y-m-d', $request->get('from_date'))->toDateString() : '';
        $data['to_date'] = ($request->has('to_date') && !empty($request->get('to_date'))) ? Carbon::createFromFormat('Y-m-d', $request->get('to_date'))->toDateString() : '';


        $data['search_text'] = $keyword;
        $data['merchant_id'] = ($request->has('merchant_id')) ? $request->get('merchant_id') : '';
        $data['center_id'] = ($request->has('center_id')) ? $request->get('center_id') : '';
        $data['user_id'] = ($request->has('user_id')) ? $request->get('user_id') : '';
        $data['lender_id'] = ($request->has('lender_id')) ? $request->get('lender_id') : '';
        $data['_application_status'] = ($request->has('_application_status')) ? $request->get('_application_status') : '';
        $data['sidebar'] = 'consumer-applications';
        ConsumerApplication::isApplicantType(true);
        //search
        $application = \App\ConsumerApplication::with('comments.user')->where(function ($query) use ($keyword) {
            $query->where('name', 'like', '%' . $keyword . '%')
                ->orWhere('email', 'like', '%' . $keyword . '%')
                ->orWhere('mobile_number', 'like', '%' . $keyword . '%');
        });

        if ($data['from_date'] && $data['to_date']) {
            //$application->whereBetween('creted_at', array( $data['from_date']." 00:00:00", $data['to_date']." 23:59:59"));
            $application->where('created_at', '>=', $data['from_date'] . " 00:00:00")->where('created_at', '<=', $data['to_date'] . " 23:59:59");
        } elseif ($data['to_date'] == '') {
            $application->where('created_at', '>=', $data['from_date']);
        } elseif ($data['from_date'] == '') {
            $application->where('created_at', '<=', $data['to_date']);
        }
        $statusarray = array();
        foreach ($this->arraygroup as $key => $arraygroup) {
            if ($arraygroup == $data['status']) {
                array_push($statusarray, $key);
            }
        }
        if ($data['status']) {
            $application->wherein('state', $statusarray);
        }

        if ($request->has('merchant_id') && $request->get('merchant_id') > 0) {
            $application->where('merchant_id', $request->get('merchant_id'));
        }
        if ($request->has('lender_id') && $request->get('lender_id') > 0) {
            $application->where('lender_id', $request->get('lender_id'));
        }
        if ($request->has('user_id') && $request->get('user_id') > 0) {
            $application->where('created_by', $request->get('user_id'));
        }
        if ($data['_application_status']) {
            $application->where('state', $data['_application_status']);
        }
        if ($data['center_id'] > 0) {
            $application->whereHas('application_element', function ($query) use ($data) {
                $query->where('center_id', $data['center_id']);
            });
        }

        if (isset($data['merchant_id']) && $data['merchant_id'] > 0) {
            $data['centers'] = MerchantLocation::where('merchant_id', $data['merchant_id'])
                ->get();
        }
        if (isset($dashboard_filter_array[0])) {
            $application = $application->whereIn('id', $dashboard_filter_array);
        }
        //search end


        $application = $application->whereNull('is_deleted')->orderBy('updated_at', 'desc');
        $_summary = $application->get();
        $application = $application->paginate(10);

        $data['consumer_applications'] = $application;
        $summary = $_summary->toArray();
        $summarycount = array_count_values(array_map(function ($item) {
            return strtolower($item['state']);
        }, $summary));
        $data['status'] = $this->status;
        foreach ($this->statusarray as $key => $value) {
            if (isset($summarycount[$key])) {
                if (!isset($data['summary'][$this->arraygroup[$key]])) {
                    $data['summary'][$this->arraygroup[$key]] = $summarycount[$key];
                } else {
                    $data['summary'][$this->arraygroup[$key]] = $data['summary'][$this->arraygroup[$key]] + $summarycount[$key];
                }
            } else {
                if (!isset($data['summary'][$this->arraygroup[$key]])) {
                    $data['summary'][$this->arraygroup[$key]] = 0;
                }
            }
        }
        $i = 0;
        if (\Auth::user()->user_type >= 5) {
            array_unshift($this->statusarray['pre approved'], 'approved');
            array_unshift($this->statusarray['waiting for decision'], 'approved');
            //array_unshift($this->statusarray['disbursement checklist done'], 'ready for disbursement');
            array_unshift($this->statusarray['disbursement checklist done'], 'disbursement query');
            array_unshift($this->statusarray['ready for disbursement'], 'disbursed');
            array_unshift($this->statusarray['cancelled'], 'disbursed');
        }
        foreach ($data['consumer_applications'] as $consumer_applications) {

            $current_status = strtolower($consumer_applications['state']);
            $data['consumer_applications'][$i]['statusarray'] = $this->statusarray[$current_status];
            $data['consumer_applications'][$i]['statusgroup'] = $this->arraygroup[$current_status];

            $i++;
        }
        $data['helptext'] = $this->helptext;
        $data['merchants'] = Merchant::where('status', 'active')->where('is_guest_active', 1)->orderBy('merchant_name', 'asc')->get(['id', 'merchant_name']);
        $data['negativeProfile'] = NegativeProfile::all();
        $data['users'] = User::where('user_type', '>=', 5)->get(['id', 'name', 'user_type']);
        $data['application_status'] = array_map('ucfirst', array_keys($this->arraygroup));
        $data['lenders'] = Lenders::get();
        $data['after_approval_status'] = $this->statusreversearray['approved'];


        return view('admin.consumer-application.index', $data);
    }

    public function wordDownload($id)
    {
        // dd($id);
        $data = ConsumerApplication::with('merchant', 'merchant.merchant_category', 'merchant_location')->find($id);

        $phpWord = new \PhpOffice\PhpWord\PhpWord();
        $title = $phpWord->addSection();
        $title->addText('Consumer Application: ', array('name' => 'Arial', 'size' => 15, 'bold' => true));
        $section = $phpWord->addSection();

        $styleCell = array('borderTopSize' => 1, 'borderTopColor' => 'black', 'borderLeftSize' => 1, 'borderLeftColor' => 'black', 'borderRightSize' => 1, 'borderRightColor' => 'black', 'borderBottomSize' => 1, 'borderBottomColor' => 'black');

        $table = $section->addTable('myOwnTableStyle', array('borderSize' => 1, 'borderColor' => '999999', 'afterSpacing' => 1, 'Spacing' => 1, 'cellMargin' => 1));
        // $table2 = $section->addTable('myOwnTableStyle');
        $table->addRow(-0.5, array('exactHeight' => 5));
        $table->addCell(2500, $styleCell)->addText('Name:');
        $table->addCell(7000, $styleCell)->addText($data->name);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Email:');
        $table->addCell(7000, $styleCell)->addText($data->email);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Mobile:');
        $table->addCell(7000, $styleCell)->addText($data->mobile_number);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Gender:');
        $table->addCell(7000, $styleCell)->addText($data->gender);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Tenure:');
        $table->addCell(7000, $styleCell)->addText($data->tenure);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Purpose:');
        $table->addCell(7000, $styleCell)->addText(isset($data->merchant->merchant_category->purpose) ? $data->merchant->merchant_category->purpose : '');
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Loan Amount:');
        $table->addCell(7000, $styleCell)->addText($data->loan_amount);

        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Merchant:');
        if ($data->merchant) {
            $table->addCell(7000, $styleCell)->addText($data->merchant->merchant_name);
        } else {
            $table->addCell(7000, $styleCell)->addText("");
        }

        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Merchant Location:');
        if ($data->merchant_location) {
            $table->addCell(7000, $styleCell)->addText($data->merchant_location->name);
        } else {
            $table->addCell(7000, $styleCell)->addText("");
        }

        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Src Merchant Name:');
        $table->addCell(7000, $styleCell)->addText($data->src_merchant_name);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Src Representative Name:');
        $table->addCell(7000, $styleCell)->addText($data->src_representative_name);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Lead Src Email:');
        $table->addCell(7000, $styleCell)->addText($data->lead_src_email);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Lead Src Phone:');
        $table->addCell(7000, $styleCell)->addText($data->lead_src_phone);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Long Link:');
        $table->addCell(7000, $styleCell)->addText($data->long_link);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Pan Card:');
        $table->addCell(7000, $styleCell)->addText($data->pan_card);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Aadhaar Card:');
        $table->addCell(7000, $styleCell)->addText($data->aadhaar_card);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('DOB:');
        $table->addCell(7000, $styleCell)->addText($data->dob);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Marital Status:');
        $table->addCell(7000, $styleCell)->addText($data->marital_status);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Current Address Line 1:');
        $table->addCell(7000, $styleCell)->addText($data->current_address_line_1);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Current Address State:');
        $table->addCell(7000, $styleCell)->addText($data->current_address_state);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Current Address City:');
        $table->addCell(7000, $styleCell)->addText($data->current_address_city);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Current Address Pincode:');
        $table->addCell(7000, $styleCell)->addText($data->current_address_pincode);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Current Address Landmark:');
        $table->addCell(7000, $styleCell)->addText($data->current_address_landmark);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Current Address Status:');
        $table->addCell(7000, $styleCell)->addText($data->current_address_status);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Permanent Address Line 1:');
        $table->addCell(7000, $styleCell)->addText($data->permanent_address_line_1);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Permanent Address State:');
        $table->addCell(7000, $styleCell)->addText($data->permanent_address_state);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Permanent Address City:');
        $table->addCell(7000, $styleCell)->addText($data->permanent_address_city);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Permanent Address Pincode:');
        $table->addCell(7000, $styleCell)->addText($data->permanent_address_pincode);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Permanent Address Landmark:');
        $table->addCell(7000, $styleCell)->addText($data->permanent_address_landmark);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Permanent Address Status:');
        $table->addCell(7000, $styleCell)->addText($data->permanent_address_status);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Alt Contact Number:');
        $table->addCell(7000, $styleCell)->addText($data->alt_contact_number);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Employee Status:');
        $table->addCell(7000, $styleCell)->addText($data->employee_status);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Monthly Income:');
        $table->addCell(7000, $styleCell)->addText($data->monthly_income);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Company Name:');
        $table->addCell(7000, $styleCell)->addText($data->company_name);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Company Number:');
        $table->addCell(7000, $styleCell)->addText($data->company_number);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Experience:');
        $table->addCell(7000, $styleCell)->addText($data->experience);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Contact Address:');
        $table->addCell(7000, $styleCell)->addText($data->contact_address);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Work Address Line 1:');
        $table->addCell(7000, $styleCell)->addText($data->work_address_line_1);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Work Address State:');
        $table->addCell(7000, $styleCell)->addText($data->work_address_state);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Work Address City:');
        $table->addCell(7000, $styleCell)->addText($data->work_address_city);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Work Address Pincode:');
        $table->addCell(7000, $styleCell)->addText($data->work_address_pincode);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Work Address Landmark:');
        $table->addCell(7000, $styleCell)->addText($data->work_address_landmark);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Co Applicant Name:');
        $table->addCell(7000, $styleCell)->addText($data->co_applicant_name);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Co Applicant Relationship:');
        $table->addCell(7000, $styleCell)->addText($data->co_applicant_relationship);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Co Applicant DOB:');
        $table->addCell(7000, $styleCell)->addText($data->co_applicant_dob);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Co Applicant Gender:');
        $table->addCell(7000, $styleCell)->addText($data->co_applicant_gender);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Co Applicant Pan Card:');
        $table->addCell(7000, $styleCell)->addText($data->co_applicant_pan_card);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Co Applicant Aadhaar Card:');
        $table->addCell(7000, $styleCell)->addText($data->co_applicant_aadhaar_card);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Co Applicant Email:');
        $table->addCell(7000, $styleCell)->addText($data->co_applicant_email);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Co Applicant Mobile Number:');
        $table->addCell(7000, $styleCell)->addText($data->co_applicant_mobile_number);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Co Applicant Address Line 1:');
        $table->addCell(7000, $styleCell)->addText($data->co_applicant_address_line_1);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Co Applicant Address State:');
        $table->addCell(7000, $styleCell)->addText($data->co_applicant_address_state);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Co Applicant Address Pincode:');
        $table->addCell(7000, $styleCell)->addText($data->co_applicant_address_pincode);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Co Applicant Address City:');
        $table->addCell(7000, $styleCell)->addText($data->co_applicant_address_city);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Co Applicant Address Landmark:');
        $table->addCell(7000, $styleCell)->addText($data->co_applicant_address_landmark);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Co Applicant Address Status:');
        $table->addCell(7000, $styleCell)->addText($data->co_applicant_address_status);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Co Applicant Required:');
        $table->addCell(7000, $styleCell)->addText($data->co_applicant_required);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Co Applicant Employee Status:');
        $table->addCell(7000, $styleCell)->addText($data->co_applicant_employee_status);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Co Applicant Monthly Income:');
        $table->addCell(7000, $styleCell)->addText($data->co_applicant_monthly_income);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Co Applicant Company Name:');
        $table->addCell(7000, $styleCell)->addText($data->co_applicant_company_name);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Co Applicant Company Number:');
        $table->addCell(7000, $styleCell)->addText($data->co_applicant_company_number);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Co Applicant Experience:');
        $table->addCell(7000, $styleCell)->addText($data->co_applicant_experience);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('State:');
        $table->addCell(7000, $styleCell)->addText($data->state);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Completed Stage:');
        $table->addCell(7000, $styleCell)->addText($data->completed_stage);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Credit Score:');
        $table->addCell(7000, $styleCell)->addText($data->credit_score);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Rejection Reason:');
        $table->addCell(7000, $styleCell)->addText($data->rejection_reason);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('Assigned To:');
        $table->addCell(7000, $styleCell)->addText($data->assigned_to);
        $table->addRow();
        $table->addCell(2500, $styleCell)->addText('MISC Info:');
        $table->addCell(7000, $styleCell)->addText($data->misc_info);

        $unique = uniqid();
        $temp_file = storage_path() . "/application_" . $unique . ".doc";
        $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
        $objWriter->save($temp_file);

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

    public function convertToCommaNumber($amount)
    {
        //setlocale(LC_MONETARY, 'en_IN');
        //$amount = money_format('%!i', $amount);
        return number_format($amount);
    }

    /*Convert Amount in number to words*/
    public function convertAmountToWords($number)
    {

        $no = round($number);
        $point = round($number - $no, 2) * 100;
        $hundred = null;
        $digits_1 = strlen($no);
        $i = 0;
        $str = array();
        $words = array('0' => '', '1' => 'One', '2' => 'Two',
            '3' => 'Three', '4' => 'Four', '5' => 'Five', '6' => 'Six',
            '7' => 'Seven', '8' => 'Eight', '9' => 'Nine',
            '10' => 'Ten', '11' => 'Eleven', '12' => 'Twelve',
            '13' => 'Thirteen', '14' => 'Fourteen',
            '15' => 'Fifteen', '16' => 'Sixteen', '17' => 'Seventeen',
            '18' => 'Eighteen', '19' => 'Nineteen', '20' => 'Twenty',
            '30' => 'Thirty', '40' => 'Forty', '50' => 'Fifty',
            '60' => 'Sixty', '70' => 'Seventy',
            '80' => 'Eighty', '90' => 'Ninety');
        $digits = array('', 'Hundred', 'Thousand', 'Lakh', 'Crore');
        while ($i < $digits_1) {
            $divider = ($i == 2) ? 10 : 100;
            $number = floor($no % $divider);
            $no = floor($no / $divider);
            $i += ($divider == 10) ? 1 : 2;
            if ($number) {
                $plural = (($counter = count($str)) && $number > 9) ? '' : null;
                $hundred = ($counter == 1 && $str[0]) ? ' and ' : null;
                $str[] = ($number < 21) ? $words[$number] .
                    " " . $digits[$counter] . $plural . " " . $hundred
                    :
                    $words[floor($number / 10) * 10]
                    . " " . $words[$number % 10] . " "
                    . $digits[$counter] . $plural . " " . $hundred;
            } else {
                $str[] = null;
            }

        }
        $str = array_reverse($str);
        $result = implode('', $str);
        $points = ($point) ?
            "." . $words[$point / 10] . " " .
            $words[$point = $point % 10] : '';
        $amtInWord = $result . ' only';
        return preg_replace('/\s+/', ' ', $amtInWord);
    }

    public function demandPromissoryNote($id)
    {
        // dd($id);
        $data = ConsumerApplication::with('merchant', 'merchant_location')->find($id);
        $amtInWord = $this->convertAmountToWords($data->loan_amount);
        $date = date_create($data->created_at);
        $create_date = date_format($date, "d F Y");

        $phpWord = new \PhpOffice\PhpWord\PhpWord();
        $section = $phpWord->addSection();
        $section->addText("                                             " . "DEMAND PROMISSORY NOTE", array('name' => 'Arial', 'size' => 11, 'bold' => true, 'text-align-last' => 'center'));

        $section->addText("\n");
        $section->addText("Rs." . $data->loan_amount . "/-", array('name' => 'Arial', 'size' => 11, 'bold' => true, 'underline' => 'single'));

        $section->addText("                                                                                                 " . "Date: " . $create_date, array('name' => 'Arial', 'size' => 11, 'bold' => true));
        $section->addText("                                                                                                 " . "Place: " . $data->current_address_city, array('name' => 'Arial', 'size' => 11, 'bold' => true));

        $section->addText("\n");
        $section->addText("ON DEMAND, I/We, " . strip_tags($data->name) . " hereby promise to pay " . $data->merchant->merchant_name . ", or order the sum of Rs." . $data->loan_amount . "/- [Rupees " . $amtInWord . "] thereon for value received together with applicable penal charges, payable as per terms and conditions.

Presentment for payment and noting and protest of this are hereby unconditionally and irrevocably waived.   ");

        /*$textrun = $section->createTextRun();
        $sentence="ON DEMAND, I/We, ".$data->name."   hereby promise to pay  " .$data->merchant->merchant_name .", or order the sum of Rs.".$data->loan_amount."/- [Rupees- ".$amtInWord."] thereon for value received together with applicable penal charges, payable as per terms and conditions.";
        $word_arr=explode(' ', $sentence);
        $styleFont = array('underline' => 'single');

        $c = 0;
        for($i = 0; $i < count($word_arr); $i++)
        {
        $c++;
        if($c == 8)
        {
        $textrun->addText($word_arr[$i].' ', $styleFont);
        }
        else
        {
        $textrun->addText($word_arr[$i]);
        }
        }*/

        $section->addText("\n");
        $section->addText("Rs." . $data->loan_amount . "/-", array('name' => 'Arial', 'size' => 11, 'bold' => true, 'underline' => 'single'));

        $section->addText("\n");
        $section->addText("(Rupees- " . $amtInWord . ")", array('name' => 'Arial', 'size' => 11, 'bold' => true, 'underline' => 'single'));

        $section->addText("\n");
        $section->addText("Name of the Borrower,");
        $section->addText("");
        $section->addText($data->name);

        // $section->addText('Arc:');
        // ImagickDraw::rectangle ( float $x1 , float $y1 , float $x2 , float $y2 );

        $unique = uniqid();
        $temp_file = storage_path() . "/application_" . $unique . ".doc";
        $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
        $objWriter->save($temp_file);

        return response()->download($temp_file)->deleteFileAfterSend(true);

    }

    public function mostImportantDocument($id)
    {
        // dd($id);
        $data = ConsumerApplication::with('merchant', 'category', 'merchant_location')->find($id);
        $date = date_create($data->created_at);
        $create_date = date_format($date, "d F Y");
        $amtInWord = $this->convertAmountToWords($data->loan_amount);

        $textStyle = array('name' => 'Times New Roman', 'size' => 9, 'bold' => false);

        $phpWord = new \PhpOffice\PhpWord\PhpWord();
        $section = $phpWord->addSection();
        //for title
        $section->addText("                                             " . "MOST IMPORTANT DOCUMENT: ", array('name' => 'Arial', 'size' => 11, 'bold' => true, 'text-align-last' => 'center'));
        //table
        $styleCell = array('borderTopSize' => 1, 'borderTopColor' => 'black', 'borderLeftSize' => 1, 'borderLeftColor' => 'black', 'borderRightSize' => 1, 'borderRightColor' => 'black', 'borderBottomSize' => 1, 'borderBottomColor' => 'black');

        $lineStyle = array('weight' => 5, 'width' => 5600, 'height' => 0, 'color' => 635552);

        $table = $section->addTable('myOwnTableStyle', array('borderSize' => 1, 'borderColor' => '999999', 'afterSpacing' => 1, 'Spacing' => 1, 'cellMargin' => 1));

        $table->addRow(-0.5, array('exactHeight' => 5));
        $table->addCell(1000, $styleCell)->addText('Sr. No.', $textStyle);
        $table->addCell(2900, $styleCell)->addText('Particulars', $textStyle);
        $table->addCell(300, $styleCell)->addText('', $textStyle);
        $table->addCell(5600, $styleCell)->addText('', $textStyle);

        $table->addRow();
        $table->addCell(1000, $styleCell)->addText('1.', $textStyle);
        $table->addCell(2900, $styleCell)->addText('Loan application date', $textStyle);
        $table->addCell(300, $styleCell)->addText(':', $textStyle);
        $table->addCell(5600, $styleCell)->addText($create_date, $textStyle);

        $table->addRow();
        $table->addCell(1000, $styleCell)->addText('2.', $textStyle);
        $table->addCell(2900, $styleCell)->addText('Date and Reference number of the Sanction Letter', $textStyle);
        $table->addCell(300, $styleCell)->addText(':', $textStyle);
        $table->addCell(5600, $styleCell)->addText('Date-' . date('d F Y') . '   Customer Reg no-DSRKATC14', $textStyle);

        $table->addRow();
        $table->addCell(1000, $styleCell)->addText('3.', $textStyle);
        $table->addCell(2900, $styleCell)->addText('Details of the Lender', $textStyle);
        $table->addCell(300, $styleCell)->addText(':', $textStyle);
        $table->addCell(5600, $styleCell)->addText('Pride Financial Services Private Limited', $textStyle);

        $table->addRow();
        $table->addCell(1000, $styleCell)->addText('4.', $textStyle);
        $table->addCell(2900, $styleCell)->addText('Details of the Borrower and Co-Borrower(s) are collectively referred as the “Borrower”', $textStyle);
        $table->addCell(300, $styleCell)->addText(':', $textStyle);
        $cell1 = $table->addCell(5600, $styleCell);
        $cell1->addText("Borrower
Name: " . $data->name . "\n" .
            "Address: " . ucwords(strtolower($data->current_address_line_1 . " " . ",near " . $data->current_address_landmark . ", " . $data->current_address_city . ", " . $data->current_address_state . "-" . $data->current_address_pincode)), $textStyle);
        if ($data->co_applicant_name) {
            $cell1->addLine($lineStyle);
            $cell1->addText("Co-Borrower" . "\n" . "Name: " . ucwords(strtolower($data->co_applicant_name)) . "\n" .
                "Address: " . ucwords(strtolower($data->co_applicant_address_line_1 . " " . ",near " . $data->co_applicant_address_landmark . ", " . $data->co_applicant_address_city . ", " . $data->co_applicant_address_state . "-" . $data->co_applicant_address_pincode)), $textStyle);
        }

        $table->addRow();
        $table->addCell(1000, $styleCell)->addText('5.', $textStyle);
        $table->addCell(2900, $styleCell)->addText('Purpose of the loan', $textStyle);
        $table->addCell(300, $styleCell)->addText(':', $textStyle);
        $table->addCell(5600, $styleCell)->addText(isset($data->merchant->merchant_category->name) ? $data->merchant->merchant_category->name : '', $textStyle);

        $table->addRow();
        $table->addCell(1000, $styleCell)->addText('6.', $textStyle);
        $table->addCell(2900, $styleCell)->addText('Loan amount sanctioned', $textStyle);
        $table->addCell(300, $styleCell)->addText(':', $textStyle);
        $table->addCell(5600, $styleCell)->addText("Rs." . $this->convertToCommaNumber($data->loan_amount) . "/-" . ' (Rupee ' . $amtInWord . ')', $textStyle);

        $table->addRow();
        $table->addCell(1000, $styleCell)->addText('7.', $textStyle);
        $table->addCell(2900, $styleCell)->addText('Availability period', $textStyle);
        $table->addCell(300, $styleCell)->addText(':', $textStyle);
        $table->addCell(5600, $styleCell)->addText('10 days from date of sanction letter', $textStyle);

        $table->addRow();
        $table->addCell(1000, $styleCell)->addText('8.', $textStyle);
        $table->addCell(2900, $styleCell)->addText('Total EMIs', $textStyle);
        $table->addCell(300, $styleCell)->addText(':', $textStyle);
        $table->addCell(5600, $styleCell)->addText('', $textStyle);

        $table->addRow();
        $table->addCell(1000, $styleCell)->addText('9.', $textStyle);
        $table->addCell(2900, $styleCell)->addText('Pending EMIs', $textStyle);
        $table->addCell(300, $styleCell)->addText(':', $textStyle);
        $table->addCell(5600, $styleCell)->addText($data->tenure, $textStyle);

        $table->addRow();
        $table->addCell(1000, $styleCell)->addText('10.', $textStyle);
        $table->addCell(2900, $styleCell)->addText('Rate of interest', $textStyle);
        $table->addCell(300, $styleCell)->addText(':', $textStyle);
        $table->addCell(5600, $styleCell)->addText('0% p.a.', $textStyle);

        $table->addRow();
        $table->addCell(1000, $styleCell)->addText('11.', $textStyle);
        $table->addCell(2900, $styleCell)->addText('Processing fee', $textStyle);
        $table->addCell(300, $styleCell)->addText(':', $textStyle);
        $table->addCell(5600, $styleCell)->addText('Zero', $textStyle);

        $table->addRow();
        $table->addCell(1000, $styleCell)->addText('12.', $textStyle);
        $table->addCell(2900, $styleCell)->addText('Repayment', $textStyle);
        $table->addCell(300, $styleCell)->addText(':', $textStyle);
        $table->addCell(5600, $styleCell)->addText('6th of every month', $textStyle);

        $table->addRow();
        $table->addCell(1000, $styleCell)->addText('13.', $textStyle);
        $table->addCell(2900, $styleCell)->addText('First EMI due date', $textStyle);
        $table->addCell(300, $styleCell)->addText(':', $textStyle);
        $table->addCell(5600, $styleCell)->addText('6th September 2018', $textStyle);

        $table->addRow();
        $table->addCell(1000, $styleCell)->addText('14.', $textStyle);
        $table->addCell(2900, $styleCell)->addText('Monthly installment amount', $textStyle);
        $table->addCell(300, $styleCell)->addText(':', $textStyle);
        $table->addCell(5600, $styleCell)->addText('', $textStyle);

        $table->addRow();
        $table->addCell(1000, $styleCell)->addText('15.', $textStyle);
        $table->addCell(2900, $styleCell)->addText('Prepayment charges', $textStyle);
        $table->addCell(300, $styleCell)->addText(':', $textStyle);
        $table->addCell(5600, $styleCell)->addText('Zero', $textStyle);

        $table->addRow();
        $table->addCell(1000, $styleCell)->addText('16.', $textStyle);
        $table->addCell(2900, $styleCell)->addText('Delayed payment charges', $textStyle);
        $table->addCell(300, $styleCell)->addText(':', $textStyle);
        $table->addCell(5600, $styleCell)->addText('0.15% per day on outstanding', $textStyle);

        $table->addRow();
        $table->addCell(1000, $styleCell)->addText('17.', $textStyle);
        $table->addCell(2900, $styleCell)->addText('Cheque/ECS/NACH dishonoured charges', $textStyle);
        $table->addCell(300, $styleCell)->addText(':', $textStyle);
        $table->addCell(5600, $styleCell)->addText("Rs.300/- per dishonor of cheque/ECS/NACH per presentation
3 successive cheque bounces/ auto debit failure will lead to loan  recall notice being issued", $textStyle);

        $table->addRow();
        $table->addCell(1000, $styleCell)->addText('18.', $textStyle);
        $table->addCell(2900, $styleCell)->addText('Undated Cheques', $textStyle);
        $table->addCell(300, $styleCell)->addText(':', $textStyle);
        $table->addCell(5600, $styleCell)->addText("We are collecting 3 undated cheques, which would be deposited if auto debit fails. Unused cheques will be returned to the borrower upon successful repayment of the loan", $textStyle);

        $table->addRow();
        $table->addCell(1000, $styleCell)->addText('19.', $textStyle);
        $table->addCell(2900, $styleCell)->addText('Details of the Merchant', $textStyle);
        $table->addCell(300, $styleCell)->addText(':', $textStyle);
        $_merchant_name = isset($data->merchant->merchant_name) ? $data->merchant->merchant_name : '';
        $_merchant_location_name = isset($data->merchant_location->name) ? $data->merchant_location->name : '';
        $_merchant_location = isset($data->merchant_location->location) ? $data->merchant_location->location : '';
        $table->addCell(5600, $styleCell)->addText("Name: " . $_merchant_name . "
Centre: " . $_merchant_location_name . "
Address: " . $_merchant_location
            , $textStyle);

        $table->addRow();
        $table->addCell(1000, $styleCell)->addText('20.', $textStyle);
        $table->addCell(2900, $styleCell)->addText('General Terms and Conditions', $textStyle);
        $table->addCell(300, $styleCell)->addText(':', $textStyle);
        $table->addCell(5600, $styleCell)->addText("General Terms and Conditions registered on the 06/07/2018 with the Sub-Registrar of Assurances Mumbai 3, Vide registration no. 6145/2018 in Book No. - Vol. No. -from pages 1 to 26 will be applicable for the Loan availed by the Borrower. The same shall form part and parcel of this Most Important Document", $textStyle);

        $section->addText("\n");
        $section->addText("Signature:" . "                                                                            " . "Signature:                                                             " . "Date:", $textStyle);
        $section->addText("Borrower: " . $data->name . "                                           " . "Co-Borrower: " . $data->co_applicant_name . "                                                      " . "Place:" . $data->co_applicant_address_city, $textStyle);

        $section->addText("");
        $section->addText("");
        $section->addText("");
        $section1 = $phpWord->addSection();
        //for title
        $section1->addText("                                             " . "INDICATIVE REPAYMENT SCHEDULE: ", array('name' => 'Arial', 'size' => 11, 'bold' => true, 'text-align-last' => 'center'));
        //table
        $styleCell = array('borderTopSize' => 1, 'borderTopColor' => 'black', 'borderLeftSize' => 1, 'borderLeftColor' => 'black', 'borderRightSize' => 1, 'borderRightColor' => 'black', 'borderBottomSize' => 1, 'borderBottomColor' => 'black');

        $table = $section1->addTable('myOwnTableStyle', array('borderSize' => 1, 'borderColor' => '999999', 'afterSpacing' => 1, 'Spacing' => 1, 'cellMargin' => 1));

        $table->addRow(-0.5, array('exactHeight' => 25));
        $table->addCell(3000, $styleCell)->addText('No. of EMI', array('bold' => true));
        $table->addCell(3000, $styleCell)->addText('Repayment Date', array('bold' => true));
        $table->addCell(3000, $styleCell)->addText('EMI Amount', array('bold' => true));

        $table->addRow(-0.5, array('exactHeight' => 25));
        $table->addCell(3000, $styleCell)->addText('1st Installment', $textStyle);
        $table->addCell(3000, $styleCell)->addText('');
        $table->addCell(3000, $styleCell)->addText('');

        $table->addRow();
        $table->addCell(3000, $styleCell)->addText('2nd Installment', $textStyle);
        $table->addCell(3000, $styleCell)->addText('');
        $table->addCell(3000, $styleCell)->addText('');

        $table->addRow();
        $table->addCell(3000, $styleCell)->addText('3nd Installment', $textStyle);
        $table->addCell(3000, $styleCell)->addText('');
        $table->addCell(3000, $styleCell)->addText('');

        $table->addRow();
        $table->addCell(3000, $styleCell)->addText('4nd Installment', $textStyle);
        $table->addCell(3000, $styleCell)->addText('');
        $table->addCell(3000, $styleCell)->addText('');

        $table->addRow();
        $table->addCell(3000, $styleCell)->addText('5nd Installment', $textStyle);
        $table->addCell(3000, $styleCell)->addText('');
        $table->addCell(3000, $styleCell)->addText('');

        $table->addRow();
        $table->addCell(3000, $styleCell)->addText('6nd Installment', $textStyle);
        $table->addCell(3000, $styleCell)->addText('');
        $table->addCell(3000, $styleCell)->addText('');

        $table->addRow();
        $table->addCell(3000, $styleCell)->addText('7nd Installment', $textStyle);
        $table->addCell(3000, $styleCell)->addText('');
        $table->addCell(3000, $styleCell)->addText('');

        $table->addRow();
        $table->addCell(3000, $styleCell)->addText('8nd Installment', $textStyle);
        $table->addCell(3000, $styleCell)->addText('');
        $table->addCell(3000, $styleCell)->addText('');

        $table->addRow();
        $table->addCell(3000, $styleCell)->addText('9nd Installment', $textStyle);
        $table->addCell(3000, $styleCell)->addText('');
        $table->addCell(3000, $styleCell)->addText('');

        $section1->addText("\n");
        $section1->addText("Signature:" . "                                                                            " . "Signature:                                                             " . "Date:", $textStyle);
        $section1->addText("Borrower: " . $data->name . "                                           " . "Co-Borrower: " . $data->co_applicant_name . "                                                      " . "Place:" . $data->co_applicant_address_city, $textStyle);

        $unique = uniqid();
        $temp_file = storage_path() . "/application_" . $unique . ".doc";
        $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
        $objWriter->save($temp_file);

        return response()->download($temp_file)->deleteFileAfterSend(true);

    }

    public function consumerNACHPDF($id)
    {
        $data = ConsumerApplication::with('bank_details', 'emi')->where('id', $id)->first();
        $pdf = App::make('snappy.pdf.wrapper');
        $data['consumer_emi'] = $data->emi;
        return view('admin.documents.nach', ['user' => $data]);

        $html = view('admin.documents.nach', ['user' => $data]);
        $pdf->loadHTML($html);
        return $pdf->download($data->name . ' consumer_nach_' . Carbon::now()->toDateString() . '.pdf');
    }

    public function consumerApplicationPDF($id)
    {
        $data = ConsumerApplication::with('merchant', 'merchant.merchant_category', 'merchant_location')->find($id);
        $pdf = App::make('snappy.pdf.wrapper');
        $html = view('admin.documents.consumer_application_report', ['response' => $data]);
        $pdf->loadHTML($html);
        return $pdf->download($data->name . ' consumer_application_' . Carbon::now()->toDateString() . '.pdf');
    }

    public function sanctionLetter($id)
    {
        // dd($id);
        $data = ConsumerApplication::with('merchant', 'merchant.merchant_category', 'merchant_location')->find($id);
        $date = date_create($data->created_at);
        $create_date = date_format($date, "d F Y");
        $amtInWord = $this->convertAmountToWords($data->loan_amount);

        $textStyle = array('name' => 'Times New Roman', 'size' => 9, 'bold' => false);

        $phpWord = new \PhpOffice\PhpWord\PhpWord();
        $section = $phpWord->addSection();
        $section->addText("Date: " . $create_date, $textStyle);
        $section->addText("");
        $section->addText("To,", $textStyle);
        $section->addText("Mr. " . $data->name, $textStyle);
        $_address1 = '';
        $_address = '';
        if (strlen($data->current_address_line_1) > 30) {
            $addresss = explode(' ', $data->current_address_line_1);
            $i = 0;
            foreach ($addresss as $item) {
                if ($i > 6) {
                    $_address1 = $item . ' ';
                } else {
                    $_address .= $item . ' ';
                }
                $i++;
            }
        }
        $section->addText(ucwords(strtolower($_address . ", near")), $textStyle);
        $section->addText(ucwords(strtolower($_address1 . ' ' . $data->current_address_landmark . ' ' . $data->current_address_city . ' ' . $data->current_address_state)), $textStyle);
        $section->addText(ucwords(strtolower($data->current_address_pincode)), $textStyle);
        $section->addText("");
        //for title
        $section->addText("                                                     " . "Subject: Sanction letter/approval for Loan", array('name' => 'Times New Roman', 'size' => 9, 'bold' => true, 'text-align-last' => 'center'));
        $section->addText("");
        // $section->addText("\n");
        $section->addText('Dear Customer,
We are pleased to inform that you are eligible for a loan facility from us as per following terms:', $textStyle);
        $section->addText("");

        //table
        $styleCell = array('borderTopSize' => 1, 'borderTopColor' => 'black', 'borderLeftSize' => 1, 'borderLeftColor' => 'black', 'borderRightSize' => 1, 'borderRightColor' => 'black', 'borderBottomSize' => 1, 'borderBottomColor' => 'black');

        $lineStyle = array('weight' => 5, 'width' => 5600, 'height' => 1, 'color' => 635552);

        $table = $section->addTable('myOwnTableStyle', array('borderSize' => 1, 'borderColor' => '999999', 'afterSpacing' => 1, 'Spacing' => 1, 'cellMargin' => 1));

        $table->addRow(-0.5, array('exactHeight' => 5));
        $table->addCell(500, $styleCell)->addText('1.', $textStyle);
        $table->addCell(3500, $styleCell)->addText('Loan application date', $textStyle);
        $table->addCell(6000, $styleCell)->addText("", $textStyle);

        $table->addRow();
        $table->addCell(500, $styleCell)->addText('2.', $textStyle);
        $table->addCell(3500, $styleCell)->addText("Details of Borrower", $textStyle);
        $cell1 = $table->addCell(6000, $styleCell);
        $cell1->addText("Name: " . ucwords(strtolower($data->name)) . "\n" .
            "Address: " . ucwords(strtolower($data->current_address_line_1 . " " . ",near " . $data->current_address_landmark . ", " . $data->current_address_city . ", " . $data->current_address_state . "-" . $data->current_address_pincode)), $textStyle);
        if ($data->co_applicant_name) {
            $cell1->addLine($lineStyle);
            $cell1->addText("Co-Borrower" . "\n" . "Name: " . ucwords(strtolower($data->co_applicant_name)) . "\n" .
                "Address: " . ucwords(strtolower($data->co_applicant_address_line_1 . " " . ",near " . $data->co_applicant_address_landmark . ", " . $data->co_applicant_address_city . ", " . $data->co_applicant_address_state . "-" . $data->co_applicant_address_pincode)), $textStyle);
        }

        $table->addRow();
        $table->addCell(500, $styleCell)->addText('3.', $textStyle);
        $table->addCell(3500, $styleCell)->addText('Validity period of this offer', $textStyle);
        $table->addCell(6000, $styleCell)->addText($data->tenure . ' days from the date of this letter', $textStyle);

        $table->addRow();
        $table->addCell(500, $styleCell)->addText('4.', $textStyle);
        $table->addCell(3500, $styleCell)->addText('Purpose of the loan', $textStyle);
        $table->addCell(6000, $styleCell)->addText(isset($data->merchant->merchant_category->name) ? $data->merchant->merchant_category->name : '', $textStyle);

        $table->addRow();
        $table->addCell(500, $styleCell)->addText('5.', $textStyle);
        $table->addCell(3500, $styleCell)->addText('Loan amount sanctioned', $textStyle);
        $table->addCell(6000, $styleCell)->addText("Rs." . $this->convertToCommaNumber($data->loan_amount) . "/-" . '(Rupees ' . $amtInWord . ')', $textStyle);

        $table->addRow();
        $table->addCell(500, $styleCell)->addText('6.', $textStyle);
        $table->addCell(3500, $styleCell)->addText('Total EMIs', $textStyle);
        $table->addCell(6000, $styleCell)->addText("");

        $table->addRow();
        $table->addCell(500, $styleCell)->addText('7.', $textStyle);
        $table->addCell(3500, $styleCell)->addText('Advance EMIs', $textStyle);
        $table->addCell(6000, $styleCell)->addText("");

        $table->addRow();
        $table->addCell(500, $styleCell)->addText('8.', $textStyle);
        $table->addCell(3500, $styleCell)->addText('Pending EMIs', $textStyle);
        $table->addCell(6000, $styleCell)->addText("");

        $table->addRow();
        $table->addCell(500, $styleCell)->addText('9.', $textStyle);
        $table->addCell(3500, $styleCell)->addText('Rate of interest', $textStyle);
        $table->addCell(6000, $styleCell)->addText("0 % p.a", $textStyle);

        $table->addRow();
        $table->addCell(500, $styleCell)->addText('10.', $textStyle);
        $table->addCell(3500, $styleCell)->addText('Processing fee (including GST)', $textStyle);
        $table->addCell(6000, $styleCell)->addText("");

        $table->addRow();
        $table->addCell(500, $styleCell)->addText('11.', $textStyle);
        $table->addCell(3500, $styleCell)->addText('Monthly installment amount', $textStyle);
        $table->addCell(6000, $styleCell)->addText("");

        $table->addRow();
        $table->addCell(500, $styleCell)->addText('12.', $textStyle);
        $table->addCell(3500, $styleCell)->addText('Prepayment charges', $textStyle);
        $table->addCell(6000, $styleCell)->addText("Zero", $textStyle);

        $table->addRow();
        $table->addCell(500, $styleCell)->addText('13.', $textStyle);
        $table->addCell(3500, $styleCell)->addText('Delayed payment charges', $textStyle);
        $table->addCell(6000, $styleCell)->addText("0.15% per day on outstanding", $textStyle);

        $table->addRow();
        $table->addCell(500, $styleCell)->addText('14.', $textStyle);
        $table->addCell(3500, $styleCell)->addText('Cheque/ECS/NACH dishonour charges', $textStyle);
        $table->addCell(6000, $styleCell)->addText("Rs 300/- per dishonor of Cheque/ ECS/NACH per presentation
3 successive cheque bounces/ auto debit failure will lead to loan recall notice being issued", $textStyle);

        $table->addRow();
        $table->addCell(500, $styleCell)->addText('15.', $textStyle);
        $table->addCell(3500, $styleCell)->addText('Post dated cheques', $textStyle);
        $table->addCell(6000, $styleCell)->addText("We are collecting 3 post dated cheques, which would be deposited if auto debit fails. Unused cheques will be shredded at our end.", $textStyle);

        $_merchant_name = isset($data->merchant->merchant_name) ? $data->merchant->merchant_name : '';
        $_merchant_location = isset($data->merchant_location->location) ? $data->merchant_location->location : '';
        $table->addRow();
        $table->addCell(500, $styleCell)->addText('16.', $textStyle);
        $table->addCell(3500, $styleCell)->addText('Details of the Merchant', $textStyle);
        $table->addCell(6000, $styleCell)->addText("Name: " . $_merchant_name . "
Address: " . $_merchant_location, $textStyle);

        $table->addRow();
        $table->addCell(500, $styleCell)->addText('17.', $textStyle);
        $table->addCell(3500, $styleCell)->addText('Documentation', $textStyle);
        $v = $table->addCell(6000, $styleCell);
        $v->addText("Submit Duly Signed to the Lender the following:", $textStyle);
        $v->addListItem('Most Important Document', 0, $textStyle);
        $v->addListItem('General Terms and Conditions', 0, $textStyle);
        $v->addListItem('Demand Promissory Note', 0, $textStyle);
        $v->addListItem('Vernacular Declaration', 0, $textStyle);

        $v->addListItem('VThree (3) Post Dated Cheques', 0, $textStyle);
        $v->addListItem('Two (2) Nach Forms', 0, $textStyle);

        $table->addRow();
        $table->addCell(500, $styleCell)->addText('18.', $textStyle);
        $table->addCell(3500, $styleCell)->addText('Loan disbursement', $textStyle);
        $table->addCell(6000, $styleCell)->addText("Post completion of the documentation you will eligible for the loan disbursement.", $textStyle);
        $section->addText("");
        $section->addText("The terms of this loan sanction shall also be governed by General Terms and Conditions, which you may kindly read before confirming your acceptance. The said documents are incorporated here by way this reference, Borrower acceptance to the terms of this letter shall and the General Terms and Conditions should be informed to the Lender by submission of a signed copy of the Most Important Document with the terms understood by the Borrowers. Further, each of the Borrowers shall be jointly and severally responsible for compliance to the terms of this loan sanction and for repayment of the loan amount disbursed.
This sanction letter will only be a letter of offer and shall stand revoked and cancelled, if there are any material changes in the proposal for which the Loan is sanctioned or; If any event occurs which, in our sole opinion is prejudicial to our interest or is likely to affect the financial condition of the Borrowers or his / her/ their ability to perform any obligations under the loan or; any statement made in the loan application or representation made is found to be incorrect or untrue or material fact has concealed or; upon completion of the validity period of 3 days of this offer unless extended by us in writing.
", $textStyle);

        $section->addText("");
        $section->addText("");

        $section->addText("Best Regards,", $textStyle);
        $section->addText("Aditya Damani", $textStyle);

        $unique = uniqid();
        $temp_file = storage_path() . "/application_" . $unique . ".doc";
        $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
        $objWriter->save($temp_file);

        return response()->download($temp_file)->deleteFileAfterSend(true);

    }

    public function declarationCumAffidavit($id)
    {
        $data = ConsumerApplication::with('merchant', 'merchant_location')->find($id);
        $date = date_create($data->created_at);
        $create_date = date_format($date, "d F Y");
        $amtInWord = $this->convertAmountToWords($data->loan_amount);

        $phpWord = new \PhpOffice\PhpWord\PhpWord();
        $section = $phpWord->addSection();

        $section->addText("                                             " . "DECLARATION CUM AFFIDAVIT", array('name' => 'Arial', 'size' => 11, 'bold' => true));
        //$section->addText("DECLARATION CUM AFFIDAVIT", array('name' => 'Arial', 'size' => 11, 'bold' => true,  'underline' => 'single','rigth' => 10360));
        $section->addText("");
        $section->addText("I, " . $data->name . "  Son / daughter of" . "____________________" . "aged about" . "____" . "years, residing at " . $data->current_address_line_1 . " " . ",near " . $data->current_address_landmark . ", " . $data->current_address_city . ", " . $data->current_address_state . "-" . $data->current_address_pincode . "  do hereby solemnly and sincerely affirm and declare as under:", array('name' => 'Arial', 'size' => 11));
        $section->addText("\n");

        //table
        $styleCell = array('borderTopSize' => 1, 'borderTopColor' => 'black', 'borderLeftSize' => 1, 'borderLeftColor' => 'black', 'borderRightSize' => 1, 'borderRightColor' => 'black', 'borderBottomSize' => 1, 'borderBottomColor' => 'black');
        $lineStyle = array('weight' => 5, 'width' => 5600, 'height' => 0, 'color' => 635552);

        $table = $section->addTable('myOwnTableStyle', array('borderSize' => 1, 'borderColor' => '999999', 'afterSpacing' => 1, 'Spacing' => 1, 'cellMargin' => 1));
        $table->addRow(-0.5, array('exactHeight' => 5));
        $table->addCell(10000, $styleCell)->addText("1. I / We has/have applied for Loan/ (strike off whichever is not applicable) to the Loan granted by " . $data->merchant->merchant_name . " (“Lender”)" . "\n" . "

    2. I / We confirm that the general terms and conditions dated [06-08-2018] (“Terms”) is acceptable to me/is and I/ we have understood the same." . "\n" . "

    3. I / We hereby declare and confirm that as I / We am / are ** illiterate / not literate in English / and I / We cannot read / understand all the terms and condition of the aforesaid Terms as stipulated by the Lender, and the declarations and confirmations of this letter have also been read and explained to me / us by Miss Shraddha Mandlik_ a representative of  Pride Financial Services Private Limited _who has countersigned this undertaking, and I / we have fully understood all the terms and conditions mentioned therein." . "\n" . "

    4. I / We hereby further declare and confirm that all the terms and conditions of sanction of the said Loan of Rs.90,000/-_(Rupees _Ninety Thousand_ only) and the Terms and all other documents stipulated by _ Pride Financial Services Private Limited  shall be binding on me / us until the clearance of the liabilities under said Loan. That the Terms have been read out and explained to me in the language known to me. " . "\n", array('name' => 'Arial', 'size' => 11));

        $unique = uniqid();
        $temp_file = storage_path() . "/application_" . $unique . ".doc";
        $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
        $objWriter->save($temp_file);

        return response()->download($temp_file)->deleteFileAfterSend(true);

    }

    public function applicationReject($id)
    {
        \App\ConsumerApplication::where('id', $id)
            ->update(['state' => $this->status['rejected']]);

        StatusLogs::insert([
            'application_id' => $id,
            'user_id' => Input::has('user_id') ? Input::get('user_id') : (Auth::user() ? Auth::user()->id : 107),
            'status' => $this->status['rejected'],
            'reason' => Input::has('rejection_reason') ? Input::get('rejection_reason') : '',
            'created_at' => Carbon::now()->toDateTimeString()
        ]);

        $user = \App\ConsumerApplication::where('id', $id)
            ->first(['email', 'name','user_id']);

        $response = ['to' => $user->email, 'subject' => 'Thanks for your loan application'];

        \Mail::send('emails.customer_loan_reject', [
            'users' => $user,
        ], function ($message) use ($response) {
            $message->bcc(_env('BACKUP_EMAIL'));
            $message->to($response['to'])->subject($response['subject']);
            //$message->cc(_env('NOTIFY_EMAIL', ''));
        });

        //event(new EventRejectApplication($id, $user->user_id));

        \Session::flash('success', 'Application successfully rejected');
        return redirect()->back();
    }

    public function getVerificationProcess($id)
    {

        $data['sidebar'] = 'consumer-applications';
        $data['consumer_applications'] = ConsumerApplication::find($id);

        $data['current_user'] = User::find($data['consumer_applications']->user_id);
        $data['verification'] = Checklist::where('application_id', $id)->first();
        return view('admin.consumer-application.verification', $data);
    }

    public function updateVerificationCheckList($item, $id, $segments, $checklist, $application, $acceptableDataReason)
    {
        switch ($item->name) {
            case 'negative_profile':

                break;
            case 'pan_validation':
                (new ConsumerDocument(new Request()))->uploadToS3('panvalidation', $id, $segments[$item->name]);
                break;
            case 'applicant_age':
                $acceptableDataReason->applicant_age = isset($segments[$item->name.'_reason']) ? $segments[$item->name.'_reason'] : '';
                $acceptableDataReason->applicant_age_other = isset($segments[$item->name.'_drp']) && $segments[$item->name.'_drp'] != 'Other' ? $segments[$item->name.'_drp'] : (isset($segments[$item->name.'_other_drp']) ? $segments[$item->name.'_other_drp'] : '');
                break;
            case 'loan_term':
                $acceptableDataReason->loan_term = isset($segments[$item->name.'_reason']) ? $segments[$item->name.'_reason'] : '';
                $acceptableDataReason->loan_term_other = isset($segments[$item->name.'_drp']) && $segments[$item->name.'_drp'] != 'Other' ? $segments[$item->name.'_drp'] : (isset($segments[$item->name.'_other_drp']) ? $segments[$item->name.'_other_drp'] : '');
                break;
            case 'monthly_income':
                $acceptableDataReason->monthly_income = isset($segments[$item->name.'_reason']) ? $segments[$item->name.'_reason'] : '';
                $acceptableDataReason->monthly_income_other = isset($segments[$item->name.'_drp']) && $segments[$item->name.'_drp'] != 'Other' ? $segments[$item->name.'_drp'] : (isset($segments[$item->name.'_other_drp']) ? $segments[$item->name.'_other_drp'] : '');
                break;
            case 'product_verification_reason':
                $acceptableDataReason->product_verification = isset($segments[$item->name]) ? $segments[$item->name] : '';
                break;
            case 'income_proof':
                $acceptableDataReason->income_proof = isset($segments[$item->name.'_reason']) ? $segments[$item->name.'_reason'] : '';
                $acceptableDataReason->income_proof_other = isset($segments[$item->name.'_drp']) && $segments[$item->name.'_drp'] != 'Other' ? $segments[$item->name.'_drp'] : (isset($segments[$item->name.'_other_drp']) ? $segments[$item->name.'_other_drp'] : '');
                break;
            case 'loan_amount':
                $acceptableDataReason->loan_amount = isset($segments[$item->name.'_reason']) ? $segments[$item->name.'_reason'] : '';
                break;
            case 'foir':
                $acceptableDataReason->foir = isset($segments[$item->name.'_reason']) ? $segments[$item->name.'_reason'] : '';
                $acceptableDataReason->foir_other = isset($segments[$item->name.'_drp']) && $segments[$item->name.'_drp'] != 'Other' ? $segments[$item->name.'_drp'] : (isset($segments[$item->name.'_other_drp']) ? $segments[$item->name.'_other_drp'] : '');
                break;
            case 'credit_score':
                $acceptableDataReason->credit_score = isset($segments[$item->name.'_reason']) ? $segments[$item->name.'_reason'] : '';
                $acceptableDataReason->credit_score_other = isset($segments[$item->name.'_drp']) && $segments[$item->name.'_drp'] != 'Other' ? $segments[$item->name.'_drp'] : (isset($segments[$item->name.'_other_drp']) ? $segments[$item->name.'_other_drp'] : '');
                break;
            case 'work_experience':
                $acceptableDataReason->work_experience = isset($segments[$item->name.'_reason']) ? $segments[$item->name.'_reason'] : '';
                $acceptableDataReason->work_experience_other = isset($segments[$item->name.'_drp']) && $segments[$item->name.'_drp'] != 'Other' ? $segments[$item->name.'_drp'] : (isset($segments[$item->name.'_other_drp']) ? $segments[$item->name.'_other_drp'] : '');
                $checklist->experience = $segments[$item->name];
                break;
            case 'linkedin':
                $checklist->linkedin = $segments[$item->name];
                break;
            case 'blood_relative':
                $acceptableDataReason->blood_relative = isset($segments[$item->name.'_reason']) ? $segments[$item->name.'_reason'] : '';
                $acceptableDataReason->blood_relative_other = isset($segments[$item->name.'_drp']) && $segments[$item->name.'_drp'] != 'Other' ? $segments[$item->name.'_drp'] : (isset($segments[$item->name.'_other_drp']) ? $segments[$item->name.'_other_drp'] : '');
                $checklist->blood_relative = $segments[$item->name];
                break;
            case 'reference_taken':
                $checklist->reference_taken = $segments[$item->name];
                break;
            case 'negative_profession':
                $acceptableDataReason->negative_profession = isset($segments[$item->name.'_reason']) ? $segments[$item->name.'_reason'] : '';
                $acceptableDataReason->negative_profession_other = isset($segments[$item->name.'_drp']) && $segments[$item->name.'_drp'] != 'Other' ? $segments[$item->name.'_drp'] : (isset($segments[$item->name.'_other_drp']) ? $segments[$item->name.'_other_drp'] : '');
                if(!Input::has('credit_policy')) {
                    //$checklist->negative_profession = $segments[$item->name];
                }
                break;
            case 'cpv_ic':
                $checklist->cpv_ic = $segments[$item->name];
                break;
            case 'utility_bill_verified':
                $checklist->utility_bill_verified = $segments[$item->name];
                break;
            case 'pl_gl_taken':
                $checklist->pl_gl_taken = $segments[$item->name];
                break;
            case 'bank_statement_file':
                $checklist->bank_statement_file = $segments[$item->name];
                $acceptableDataReason->bank_statement_file = isset($segments[$item->name.'_reason']) ? $segments[$item->name.'_reason'] : '';
                $acceptableDataReason->bank_statement_file_other = isset($segments[$item->name.'_drp']) && $segments[$item->name.'_drp'] != 'Other' ? $segments[$item->name.'_drp'] : (isset($segments[$item->name.'_other_drp']) ? $segments[$item->name.'_other_drp'] : '');
                break;
            case 'out_cb_eb':
                $acceptableDataReason->out_cb_eb = isset($segments[$item->name.'_reason']) ? $segments[$item->name.'_reason'] : '';
                $acceptableDataReason->out_cb_eb_other = isset($segments[$item->name.'_drp']) && $segments[$item->name.'_drp'] != 'Other' ? $segments[$item->name.'_drp'] : (isset($segments[$item->name.'_other_drp']) ? $segments[$item->name.'_other_drp'] : '');
                $checklist->out_cb_eb = $segments[$item->name];
                break;
            case 'abb_emi':
                $checklist->abb_emi = $segments[$item->name];
                $acceptableDataReason->abb_emi = isset($segments[$item->name.'_reason']) ? $segments[$item->name.'_reason'] : '';
                $acceptableDataReason->abb_emi_other = isset($segments[$item->name.'_drp']) && $segments[$item->name.'_drp'] != 'Other' ? $segments[$item->name.'_drp'] : (isset($segments[$item->name.'_other_drp']) ? $segments[$item->name.'_other_drp'] : '');
                break;
            case 'in_cb':
                $checklist->in_cb = $segments[$item->name];
                break;
            case 'min_balance_charge':
                $acceptableDataReason->min_balance_charge = isset($segments[$item->name.'_reason']) ? $segments[$item->name.'_reason'] : '';
                $acceptableDataReason->min_balance_charge_other = isset($segments[$item->name.'_drp']) && $segments[$item->name.'_drp'] != 'Other' ? $segments[$item->name.'_drp'] : (isset($segments[$item->name.'_other_drp']) ? $segments[$item->name.'_other_drp'] : '');
                $checklist->min_balance_charge = $segments[$item->name];
                break;
            case 'facebook':
                $checklist->facebook = $segments[$item->name];
                break;
            case 'tele_verification':
                $checklist->tele_verification = $segments[$item->name];
                break;
            case 'pan_card':

                break;
            case 'customer_age':

                break;
            case 'product_verification':

                break;
            case 'suspicious_file_input':
                $acceptableDataReason->suspicious_file_input = isset($segments[$item->name.'_reason']) ? $segments[$item->name.'_reason'] : '';
                $acceptableDataReason->suspicious_file_input_other = isset($segments[$item->name.'_drp']) && $segments[$item->name.'_drp'] != 'Other' ? $segments[$item->name.'_drp'] : (isset($segments[$item->name.'_other_drp']) ? $segments[$item->name.'_other_drp'] : '');
                break;
            case 'aadhar':

                break;
            case 'date_of_birth':

                break;
            case 'dpd':
                $acceptableDataReason->dpd = isset($segments[$item->name.'_reason']) ? $segments[$item->name.'_reason'] : '';
                $acceptableDataReason->dpd_other = isset($segments[$item->name.'_drp']) && $segments[$item->name.'_drp'] != 'Other' ? $segments[$item->name.'_drp'] : (isset($segments[$item->name.'_other_drp']) ? $segments[$item->name.'_other_drp'] : '');
                break;
            case 'writeen_settled_suit':
                $acceptableDataReason->writeen_settled_suit = isset($segments[$item->name.'_reason']) ? $segments[$item->name.'_reason'] : '';
                $acceptableDataReason->writeen_settled_suit_other = isset($segments[$item->name.'_drp']) && $segments[$item->name.'_drp'] != 'Other' ? $segments[$item->name.'_drp'] : (isset($segments[$item->name.'_other_drp']) ? $segments[$item->name.'_other_drp'] : '');
                break;
            case 'enquiries':

                break;
            case 'salary':
                $acceptableDataReason->salary = isset($segments[$item->name.'_reason']) ? $segments[$item->name.'_reason'] : '';
                $acceptableDataReason->salary_other = isset($segments[$item->name.'_drp']) && $segments[$item->name.'_drp'] != 'Other' ? $segments[$item->name.'_drp'] : (isset($segments[$item->name.'_other_drp']) ? $segments[$item->name.'_other_drp'] : '');
                $checklist->salary = $segments[$item->name];
                break;
            case 'no_debit_chq_bounce_ecs':
                $checklist->no_debit_chq_bounce_ecs = $segments[$item->name];
                break;
            case 'regular_high_value':
                $checklist->regular_high_value = $segments[$item->name];
                break;
            case 'average_balance':
                $checklist->average_balance = $segments[$item->name];
                break;
            case 'mca':
                (new ConsumerDocument(new Request()))->uploadToS3('mca', $id, $segments[$item->name]);
                break;
            case 'call_recording':
                (new ConsumerDocument(new Request()))->uploadToS3('call_recording', $id, $segments[$item->name]);
                break;
            case 'prode':
                (new ConsumerDocument(new Request()))->uploadToS3('prode42', $id, $segments[$item->name]);
                break;
            case 'credit_approval_video':
                $element = ConsumerApplicationElement::where('application_id', $id)->first(['id']);
                if (isset($element->id)) {
                    $applicationElement = ConsumerApplicationElement::find($element->id);
                } else {
                    $applicationElement = new ConsumerApplicationElement();
                }
                $applicationElement->credit_approval_video = $segments[$item->name];
                $applicationElement->save();
                break;
            case 'hypothecation_agreement':
                (new ConsumerDocument(new Request()))->uploadToS3('hypothecation_agreement', $id, $segments[$item->name]);
                break;
            case 'joining_date':
                $date = Carbon::createFromFormat('m/Y', $segments[$item->name])->toDateString();
                $checklist->joining_date = $date;
                break;
            case 'designation':
                $element = ConsumerApplicationElement::where('application_id', $id)->first(['id']);
                if (isset($element->id)) {
                    $applicationElement = ConsumerApplicationElement::find($element->id);
                } else {
                    $applicationElement = new ConsumerApplicationElement();
                }
                $applicationElement->designation = $segments[$item->name];
                $applicationElement->save();
                break;
            case 'department':
                $element = ConsumerApplicationElement::where('application_id', $id)->first(['id']);
                if (isset($element->id)) {
                    $applicationElement = ConsumerApplicationElement::find($element->id);
                } else {
                    $applicationElement = new ConsumerApplicationElement();
                }
                $applicationElement->department = $segments[$item->name];
                $applicationElement->save();
                break;
            case 'contact':
                $element = ConsumerApplicationElement::where('application_id', $id)->first(['id']);
                if (isset($element->id)) {
                    $applicationElement = ConsumerApplicationElement::find($element->id);
                } else {
                    $applicationElement = new ConsumerApplicationElement();
                }
                $applicationElement->contact = $segments[$item->name];
                $applicationElement->save();
                break;
            case 'product_name':
                $element = ConsumerApplicationElement::where('application_id', $id)->first(['id']);
                if (isset($element->id)) {
                    $applicationElement = ConsumerApplicationElement::find($element->id);
                } else {
                    $applicationElement = new ConsumerApplicationElement();
                }
                $applicationElement->product_name = $segments[$item->name];
                $applicationElement->save();
                break;
            case 'verify_pro_crt':
                $checklist->verify_pro_crt = $segments[$item->name];
                break;
            case 'address_document_mapping_current_address':
                $checklist->current_address_document = $segments[$item->name];
                break;
            case 'address_document_mapping_permanent_address':
                $checklist->permanent_address_document = $segments[$item->name];
                break;
            case 'official_email':
                $element = ConsumerApplicationElement::where('application_id', $id)->first(['id']);
                if (isset($element->id)) {
                    $applicationElement = ConsumerApplicationElement::find($element->id);
                } else {
                    $applicationElement = new ConsumerApplicationElement();
                }
                $applicationElement->work_email = $segments[$item->name];
                $applicationElement->save();
                break;
            case 'office_address':

                break;
            case 'utility_bill':
                (new ConsumerDocument(new Request()))->uploadToS3('utilitybillvalidation', $id, $segments[$item->name]);
                break;
            case 'residing':
                $applicationData['consumer_applications'] = $application;
                $negativeArea = $this->getNegativeAreaList($applicationData);
                $checklist->residing = $negativeArea ? 1 : $segments[$item->name];
                break;
            case 'cpv[]':
                if ($segments['cpv']) {
                    $document = (new ConsumerDocument(new Request()));
                    foreach ($segments['cpv'] as $segment) {
                        $document->uploadToS3('cpv', $id, $segment);
                    }
                }
                break;
            case 'nach':
                (new ConsumerDocument(new Request()))->uploadToS3('nach', $id, $segments[$item->name]);
                break;
            case 'signed_loan_agreement':
                (new ConsumerDocument(new Request()))->uploadToS3('agreement', $id, $segments[$item->name]);
                break;
            case 'advance_payment':
                (new ConsumerDocument(new Request()))->uploadToS3('pro_forma_invoice', $id, $segments[$item->name]);
                break;
            case 'proform':
                (new ConsumerDocument(new Request()))->uploadToS3('proforma', $id, $segments[$item->name]);
                break;
            case 'quotation_bill':
                (new ConsumerDocument(new Request()))->uploadToS3('quotation_bill', $id, $segments[$item->name]);
                break;
            default:
                if (isset($segments[$item->name]))
                    (new ConsumerDocument(new Request()))->uploadToS3($item->name, $id, $segments[$item->name]);
                break;

        }
    }

    public function generateCAMReport($id, $softdeleteStatus = true){

        $application = ConsumerApplication::with('proFormaInvoice','creditReport','bank_details', 'merchant','emi.offer', 'invoice',
            'merchant.merchant_category','foir','emi_payment','trade_advance','finBitDataBorrower','finBitDataCoBorrower','disbursement_log',
            'ConsumerApplicationElement.product','cibilReportBorrower','cibilReportCoBorrower', 'emi')->where('id',$id)->first();
        $is_avanse = false;
        if(!empty($application)) {
            $is_avanse = $application->isAvanse();
        }
        $is_avanse = true;
        $request = new Request(['id' => $id]);


        $subvention = (new AvanseDisbursementInstruction($request))->getSubventionAmountAvanse($application);
        $withheld_percent = LiabilityLog::where('application_id', $id)->orderBy('created_at', 'desc')->first(['liability_percent', 'liability_amount']);
        if($application->lender_id == AvanseServices::$lender_id) {
            $subv_amount = $subvention['Net'];
            if($application->emi->subvention && $application->merchant->is_gst && $application->merchant->is_gst == 1){
                $subv_amount = $subvention['WithGST'];
            }
            $net_disbursement = (new AvanseProcesses($request))->getNetAmountAsPerAvanse($subv_amount);
            if($application->proFormaInvoice->processing_fee_by_merchant == 1){
                $net_disbursement = round($net_disbursement - $application->emi->processing_fee);
            }
            if(isset($withheld_percent->liability_percent) && $withheld_percent->liability_percent){
                $hold_amount = $net_disbursement * $withheld_percent->liability_percent/100;
                $net_disbursement = round($net_disbursement - $hold_amount);
            }
        }else{
            $net_disbursement = round((new ConsumerApplicationController())->getDisbursementAmount($id));
        }

        if(empty($application->application_element->product->name)){
            $application->application_element->product_name = $this->getProductName($application->application_element->product_name);
        }

        $this->isInternal = true;
        $verificationList = $this->verficationChecklist($id);

        $verificationListData = [];
        foreach ($verificationList as $item){
            $verificationListData[$item['key']] = $item;
        }
        unset($verificationList);

        $policies = [
                'residing' => [
                    'policy_followed' => [
                        'name' => 'Residing in Non-Negative Area',
                        'status' => true,
                        'reasons' => []
                    ],
                    'exceptions_taken' => [
                        'name' => 'Residing in Negative Area',
                        'status' => true,
                        'reasons' => []
                    ]
                ],

                'negative_profession' => [
                    'policy_followed' => [],
                    'exceptions_taken' => [
                        'name' => 'Negative Profession',
                        'status' => true,
                        'reasons' => []
                    ]
                ],
                'blood_relative' => [
                    'policy_followed' => [],
                    'exceptions_taken' => [
                        'name' => 'Co-Applicant is not a Blood Relative',
                        'status' => true,
                        'reasons' => []
                    ]
                ],
                'applicant_age' => [
                    'policy_followed' => [
                        'name' => 'Customer Age is {}',
                        'status' => true,
                        'reasons' => []
                    ],
                    'exceptions_taken' => [
                        'name' => 'Customer Age is {}',
                        'status' => true,
                        'reasons' => []
                    ]
                ],
                'loan_term' => [
                    'policy_followed' => [
                        'name' => 'Loan Term is {} months',
                        'status' => true,
                        'reasons' => []
                    ],
                    'exceptions_taken' => [
                        'name' => 'Loan Term is {} months',
                        'status' => true,
                        'reasons' => []
                    ]
                ],
                'monthly_income' => [
                    'policy_followed' => [
                        'name' => 'Monthly Income is {}',
                        'status' => true,
                        'reasons' => []
                    ],
                    'exceptions_taken' => [
                        'name' => 'Monthly Income is {}',
                        'status' => true,
                        'reasons' => []
                    ]
                ],
                'income_proof' => [
                    'policy_followed' => [
                        'name' => 'Income Proof taken',
                        'status' => true,
                        'reasons' => []
                    ],
                    'exceptions_taken' => [
                        'name' => 'Income Proof not taken',
                        'status' => true,
                        'reasons' => []
                    ]
                ],
                'foir' => [
                    'policy_followed' => [
                        'name' => 'FOIR is {}',
                        'status' => true,
                        'reasons' => []
                    ],
                    'exceptions_taken' => [
                        'name' => 'FOIR is {}',
                        'status' => true,
                        'reasons' => []
                    ]
                ],
                'loan_amount' => [
                    'policy_followed' => [],
                    'exceptions_taken' => [
                        'name' => 'Loan Amount is {}',
                        'status' => true,
                        'reasons' => []
                    ]
                ],
                'writeen_settled_suit' => [
                    'policy_followed' => [
                        'name' => 'Good Repayment History',
                        'status' => true,
                        'reasons' => []
                    ],
                    'exceptions_taken' => [
                        'name' => 'Negative Status of Loan',
                        'status' => true,
                        'reasons' => []
                    ]
                ],
                'credit_score' => [
                    'policy_followed' => [
                        'name' => 'Credit Score is {}',
                        'status' => true,
                        'reasons' => []
                    ],
                    'exceptions_taken' => [
                        'name' => 'Credit Score is {}',
                        'status' => true,
                        'reasons' => []
                    ]
                ],
                'dpd' => [
                    'policy_followed' => [
                        'name' => 'No DPDs',
                        'status' => true,
                        'reasons' => []
                    ],
                    'exceptions_taken' => [
                        'name' => '{} DPD',
                        'status' => true,
                        'reasons' => []
                    ]
                ],
                'work_experience' => [
                    'policy_followed' => [
                        'name' => 'Work stability at current company is {} months',
                        'status' => true,
                        'reasons' => []
                    ],
                    'exceptions_taken' => [
                        'name' => 'Work stability at current company is {} months',
                        'status' => true,
                        'reasons' => []
                    ]
                ],
                'out_cb_eb' => [
                    'policy_followed' => [
                        'name' => 'No ECS/Cheque Bounces',
                        'status' => true,
                        'reasons' => []
                    ],
                    'exceptions_taken' => [
                        'name' => 'ECS/Cheque Bounces',
                        'status' => true,
                        'reasons' => []
                    ]
                ],
                'min_balance_charge' => [
                    'policy_followed' => [],
                    'exceptions_taken' => [
                        'name' => 'Minimum Balance Charges charged',
                        'status' => true,
                        'reasons' => []
                    ]
                ],
                'abb_emi' => [
                    'policy_followed' => [
                        'name' => 'ABB/EMI is {}',
                        'status' => true,
                        'reasons' => []
                    ],
                    'exceptions_taken' => [
                        'name' => 'ABB/EMI is not {}',
                        'status' => true,
                        'reasons' => []
                    ]
                ],
                'bank_statement_file' => [
                    'policy_followed' => [
                        'name' => 'Latest {} Bank Statement taken',
                        'status' => true,
                        'reasons' => []
                    ],
                    'exceptions_taken' => [
                        'name' => 'Latest {} Bank Statement not  taken',
                        'status' => true,
                        'reasons' => []
                    ]
                ],
                'salary' => [
                    'policy_followed' => [
                        'name' => 'Salary seen in Bank Statement',
                        'status' => true,
                        'reasons' => []
                    ],
                    'exceptions_taken' => [
                        'name' => 'Salary not seen in Bank Statement',
                        'status' => true,
                        'reasons' => []
                    ]
                ],
                'reference_taken' => [
                    'policy_followed' => [
                        'name' => 'References taken',
                        'status' => true,
                        'reasons' => []
                    ],
                    'exceptions_taken' => [
                        'name' => 'References not taken',
                        'status' => true,
                        'reasons' => []
                    ]
                ],
                'suspicious_file_input' => [
                    'policy_followed' => [],
                    'exceptions_taken' => [
                        'name' => 'Suspicious Bank Statement',
                        'status' => true,
                        'reasons' => []
                    ]
                ],
                'personal_discussion_done' => [
                    'policy_followed' => [
                        'name' => 'Personal Discussion Done',
                        'status' => true,
                        'reasons' => []
                    ],
                    'exceptions_taken' => []
                ],
        ];

        $policies = $this->getValidatePolicy($policies, $verificationListData, $application);
        $pdf = App::make('snappy.pdf.wrapper');
        $statusLogs = StatusLogs::where('application_id', $id)->where('status','approved')->first(['user_id']);
        $approved_by = '';
        if(isset($statusLogs->user_id)){
            $approved_by = User::where('id',$statusLogs->user_id)->first(['name']);
        }
        $view  = 'front.cam-report';
        $foir = 0;
        $multistage_disb = 0;
        $report = [];
        if ($is_avanse) {
            $view = 'admin.documents.avanse.cam_report';
            if($application->lender_id == AvanseServices::$lender_id){
                $avanseProcesses = new AvanseProcesses(new Request(['id' => $id]));
                $application->loan_amount = $avanseProcesses->getNetAmountAsPerAvanse();
                $foir = $avanseProcesses->getFoirByAvanse($id);
            }else{
                $application->loan_amount = $application->approved_amount;
            }

            /* Downpayment amount calc */
            if($application->proFormaInvoice->merchant_collected_advance_amount == 0) {
                if ($application->emi->offer->advance_type == 'emi') {
                    $application->emi->tenure = $application->emi->tenure - $application->emi->advance_emi;
                    $application->emi->advance_emi = $application->emi->emi * $application->emi->advance_emi;
                }
            }else{
                $application->emi->advance_emi = 0;
            }

        }

        if($application->lender_id != AvanseServices::$lender_id) {
            $foir = count($application->creditReport) >= 1 && $application->creditReport[0]->foirIncludingCFEMI ? $application->creditReport[0]->foirIncludingCFEMI : $foir;
            $multiStageDisbursement = new MultiStageDisbursement();
            if ($multiStageDisbursement->canPartialDisbursement($application->emi->offer->id, $application)) {
                $disb_req = new Request(['id' => $id]);
                $multistage_disb = $this->getPartialDisbursementData_v2($disb_req, $multiStageDisbursement, $application)->getData();
            }
        }

        if($application->lender_id == AvanseServices::$lender_id || $application->lender_id == Services::$lender_id){
            $manual_score = ConsumerApplicationFiles::where('consumer_application_id', $id)->where('file_type', 'equifax_report')->whereNull('deleted_at')->orderBy('created_at','desc')->first();
            $credit_score = CreditReport::where('application_id', $id)->whereNull('deleted_at')->orderBy('created_at','desc')->first();
            $credit_score_app = "";
            $credit_score_coapp = "";
                if(isset($manual_score) && $manual_score->bureau_report_score != ''){
                    if($manual_score->applicant_type == 1){
                        $credit_score_app = $manual_score->bureau_report_score;
                    }elseif($manual_score->applicant_type == 2){
                        $credit_score_coapp = $manual_score->bureau_report_score;
                    }
                }elseif(isset($credit_score)){
                    if($credit_score->applicant_type == 1){
                        $credit_score_app = $credit_score->Score;
                    }elseif($credit_score->applicant_type == 2){
                        $credit_score_coapp = $credit_score->Score;
                    }
                }

            $report = [
                'credit_app' => $credit_score_app ?? '',
                'credit_coapp' => $credit_score_coapp ?? ''
            ];
        }else{
            $files = ConsumerApplicationFiles::where('consumer_application_id', $id)->where('file_type', 'equifax_report')->whereNull('deleted_at')->get();
            foreach($files as $file){
                if($file->bureau_report_type == 'Equifax v2.0'){
                    if($file->applicant_type == 1){
                        $app_equifax = $file->bureau_report_score;
                    }elseif($file->applicant_type == 2){
                        $coapp_equifax = $file->bureau_report_score;
                    }
                }elseif($file->bureau_report_type == 'CIBIL CreditVision'){
                    if($file->applicant_type == 1){
                        $app_cibil = $file->bureau_report_score;
                    }elseif($file->applicant_type == 2){
                        $coapp_cibil = $file->bureau_report_score;
                    }
                }
            }

            $report = [
                'app_equifax' => $app_equifax ?? '',
                'coapp_equifax' => $coapp_equifax ?? '',
                'app_cibil' => $app_cibil ?? '',
                'coapp_cibil' => $coapp_cibil ?? '',
            ];
        }

        //return $policies;
        $propertiesCAM = ['application' => $application, 'foir' => $foir, 'policies' => $this->normalizePolicyData($policies),
            'approved_by' => $approved_by->name ?? '',
            'net_dis' => $net_disbursement, 'subventionWithGST' => $subvention['WithGST'], 'gst_on_subvention' => $subvention['gst_on_subvention'], 'subvention' => $subvention['Net'],
            'withheld_percent' => $withheld_percent, 'multistage' => $multistage_disb, 'report' => $report];

        // $cat = _env('APP_CONNECTION') ? 24 : 6;
        // if($application->purpose == $cat){
            $approvedLog = StatusLogs::where('application_id', $application->id)->where('status', 'approved')->orderBy('created_at', 'asc')->first(['created_at']);
            $approvedDate = null;
            if ($approvedLog) {
                $approvedDate = Carbon::parse($approvedLog->created_at);
            }
            if(isset($application->proFormaInvoice->insurance_premium_applicable) && $application->proFormaInvoice->insurance_premium_applicable == 1){
                // $tenure_in_years = ceil($application->tenure / 12);
                $tenure_in_years = $application->proFormaInvoice->insurance_coverage ? $application->proFormaInvoice->insurance_coverage : 1;
                $propertiesCAM['splitInsurance'] = $this->insuranceCalculation($application->approved_amount,$application->application_element->discount_by_cf,$application->emi->processing_fee,1, $tenure_in_years, $approvedDate, $application->application_element->inverter_gross_project_amount ?? 0);
            }
        // }

        if ($this->viewReturn) {
            return view($view, $propertiesCAM);
        }
        $camReport = $pdf->loadView($view, $propertiesCAM)->setOption('encoding', 'UTF-8')->setPaper('a4')->setOrientation('portrait');

        /* Uncomment below lines if you want to download and see the cam report in local*/
        //Storage::disk('storage')->put('Cam-Report-'.$id.'.pdf', $camReport->output());
        //return $application;

        $document = new ConsumerDocument(new Request());
        if($softdeleteStatus){
            ConsumerApplicationFiles::where('consumer_application_id',$id)->where('file_type','credit_appraisal_memo')->delete();
        }
        $document->uploadToS3('credit_appraisal_memo', $id, $camReport->output());
        if($application->lender_id != AvanseServices::$lender_id) {
            Session::flash('success', 'Credit appraisal memo generated successfully');
            return \redirect()->back();
        }
        return true;

        //return $camReport->inline();
    }

    public function getValidatePolicy($policies, $verificationList, $application){
        foreach ($policies as $key => $policy){


            if(isset($verificationList[$key]['view'])){
                if(isset($policies[$key]['exceptions_taken']) && $policies[$key]['exceptions_taken']) {
                    $policies[$key]['exceptions_taken']['reason'][] = isset($verificationList[$key]['view']['selectDropDownValue']) ? $verificationList[$key]['view']['selectDropDownValue'] : '';
                    if(isset($verificationList[$key]['value'])) {

                        $name_Values = isset($verificationList[$key]['view']['Errors']) && $verificationList[$key]['view']['Errors'] ? implode(',',$verificationList[$key]['view']['Errors']) : $verificationList[$key]['value'];
                        $policies[$key]['exceptions_taken']['name'] = str_replace('{}', $name_Values, $policies[$key]['exceptions_taken']['name']);
                    }
                }
                if(isset($policies[$key]['policy_followed']) && $policies[$key]['policy_followed']) {
                    $policies[$key]['policy_followed']['reason'][] = isset($verificationList[$key]['view']['selectDropDownValue']) ? $verificationList[$key]['view']['selectDropDownValue'] : '';
                    if(isset($verificationList[$key]['value'])) {

                        $name_Values = isset($verificationList[$key]['view']['Errors']) && $verificationList[$key]['view']['Errors'] ? implode(',',$verificationList[$key]['view']['Errors']) : $verificationList[$key]['value'];
                        $policies[$key]['policy_followed']['name'] = str_replace('{}', $name_Values, $policies[$key]['policy_followed']['name']);
                    }
                }
            }

            switch ($key){
                case 'residing':
                    if(isset($verificationList[$key]['status']) && $verificationList[$key]['status'] && isset($policies[$key]['exceptions_taken']) && $policies[$key]['exceptions_taken']){
                        $policies[$key]['policy_followed'] = [];
                    }elseif(isset($verificationList[$key]['status']) && isset($policies[$key]['policy_followed']) && $policies[$key]['policy_followed']){
                        $policies[$key]['exceptions_taken'] = [];
                    }
                    break;
                case 'negative_profession':
                    if(isset($verificationList[$key]['status']) && !$verificationList[$key]['status'] && isset($policies[$key]['exceptions_taken']) && $policies[$key]['exceptions_taken']){
                        $policies[$key]['exceptions_taken'] = [];
                    }
                    break;
                case 'salary':
                    if(isset($verificationList[$key]['status']) && !$verificationList[$key]['view']['Acceptable'] && isset($policies[$key]['exceptions_taken']) && $policies[$key]['exceptions_taken']){
                        $policies[$key]['policy_followed'] = [];
                    }elseif(isset($verificationList[$key]['status']) && isset($policies[$key]['policy_followed']) && $policies[$key]['policy_followed']){
                        $policies[$key]['exceptions_taken'] = [];
                    }

                    if(in_array($application->employee_status, ['Self Employed - Professional', 'Self Employed - Business', 'HOUSEWIFE', 'BUSINESS', 'UNEMPLOYED', 'PENSIONER'])){
                        $policies[$key]['policy_followed'] = [];
                        $policies[$key]['exceptions_taken'] = [];
                    }

                    break;
                case 'writeen_settled_suit':
                    if(isset($verificationList[$key]['status']) && $verificationList[$key]['view']['Acceptable'] && isset($policies[$key]['exceptions_taken']) && $policies[$key]['exceptions_taken']){
                        $policies[$key]['policy_followed'] = [];
                    }elseif(isset($verificationList[$key]['status']) && isset($policies[$key]['policy_followed']) && $policies[$key]['policy_followed']){
                        $policies[$key]['exceptions_taken'] = [];
                    }
                    break;
                case 'bank_statement_file':
                    if(isset($verificationList[$key]['status']) && !$verificationList[$key]['view']['Acceptable'] && isset($policies[$key]['exceptions_taken']) && $policies[$key]['exceptions_taken']){
                        $policies[$key]['policy_followed'] = [];
                    }elseif(isset($verificationList[$key]['status']) && isset($policies[$key]['policy_followed']) && $policies[$key]['policy_followed']){
                        $policies[$key]['exceptions_taken'] = [];
                    }
                    break;
                case 'blood_relative':
                    if(isset($verificationList[$key]['status']) && !$verificationList[$key]['status'] && isset($policies[$key]['exceptions_taken']) && $policies[$key]['exceptions_taken']){
                        $policies[$key]['policy_followed'] = [];
                    }else{
                        $policies[$key]['exceptions_taken'] = [];
                    }
                    break;
                case 'applicant_age':
                    if(isset($verificationList[$key]['status']) && !$verificationList[$key]['view']['Acceptable'] && isset($policies[$key]['exceptions_taken']) && $policies[$key]['exceptions_taken']){
                        $policies[$key]['policy_followed'] = [];
                    }elseif(isset($verificationList[$key]['status']) && isset($policies[$key]['policy_followed']) && $policies[$key]['policy_followed']){
                        $policies[$key]['exceptions_taken'] = [];
                    }
                    break;
                case 'loan_term':
                    if(isset($verificationList[$key]['status']) && !$verificationList[$key]['view']['Acceptable'] && isset($policies[$key]['exceptions_taken']) && $policies[$key]['exceptions_taken']){
                        $policies[$key]['policy_followed'] = [];
                        if($verificationList[$key]['view']['Errors']) {
                            $policies[$key]['exceptions_taken']['name'] = implode(',',$verificationList[$key]['view']['Errors']);
                        }
                    }elseif(isset($verificationList[$key]['status']) && isset($policies[$key]['policy_followed']) && $policies[$key]['policy_followed']){
                        $policies[$key]['exceptions_taken'] = [];
                    }
                    break;
                case 'monthly_income':
                    if(isset($verificationList[$key]['status']) && !$verificationList[$key]['status'] && isset($policies[$key]['exceptions_taken']) && $policies[$key]['exceptions_taken']){
                        $policies[$key]['policy_followed'] = [];
                    }elseif(isset($verificationList[$key]['status']) && isset($policies[$key]['policy_followed']) && $policies[$key]['policy_followed']){
                        $policies[$key]['exceptions_taken'] = [];
                    }
                    break;
                case 'income_proof':
                    if(isset($verificationList[$key]['status']) && isset($verificationList[$key]['view']['Acceptable']) && !$verificationList[$key]['view']['Acceptable'] && isset($policies[$key]['exceptions_taken']) && $policies[$key]['exceptions_taken']){
                        $policies[$key]['policy_followed'] = [];
                    }elseif(isset($verificationList[$key]['status']) && isset($policies[$key]['policy_followed']) && $policies[$key]['policy_followed']){
                        $policies[$key]['exceptions_taken'] = [];
                    }
                    break;
                case 'loan_amount':
                    if(isset($verificationList[$key]['status']) && !$verificationList[$key]['view']['Acceptable'] && isset($policies[$key]['exceptions_taken']) && $policies[$key]['exceptions_taken']){
                        if($verificationList[$key]['view']['Errors']) {
                            $policies[$key]['exceptions_taken']['name'] = implode(',',$verificationList[$key]['view']['Errors']);
                        }
                        $policies[$key]['policy_followed'] = [];
                    }else{
                        $policies[$key]['exceptions_taken'] = [];
                    }
                    break;
                case 'dpd':
                    if(isset($verificationList[$key]['status']) && $verificationList[$key]['view']['Acceptable'] && isset($policies[$key]['exceptions_taken']) && $policies[$key]['exceptions_taken']){
                        $policies[$key]['policy_followed'] = [];
                    }elseif(isset($verificationList[$key]['status']) && isset($policies[$key]['policy_followed']) && $policies[$key]['policy_followed']){
                        $policies[$key]['exceptions_taken'] = [];
                    }
                    break;
                case 'suspicious_file_input':
                    if(isset($verificationList[$key]['status']) && $verificationList[$key]['view']['Acceptable'] && isset($policies[$key]['exceptions_taken']) && $policies[$key]['exceptions_taken']){
                        $policies[$key]['policy_followed'] = [];
                    }else{
                        $policies[$key]['exceptions_taken'] = [];
                    }
                    break;
                case 'out_cb_eb':
                    if(isset($verificationList[$key]['status']) && $verificationList[$key]['view']['Acceptable'] && isset($policies[$key]['exceptions_taken']) && $policies[$key]['exceptions_taken']){
                        $policies[$key]['policy_followed'] = [];
                    }elseif(isset($verificationList[$key]['status']) && isset($policies[$key]['policy_followed']) && $policies[$key]['policy_followed']){
                        $policies[$key]['exceptions_taken'] = [];
                    }
                    break;
                case 'abb_emi':
                    if(isset($verificationList[$key]['status']) && !$verificationList[$key]['view']['Acceptable'] && isset($policies[$key]['exceptions_taken']) && $policies[$key]['exceptions_taken']){
                        $policies[$key]['policy_followed'] = [];
                    }elseif(isset($verificationList[$key]['status']) && isset($policies[$key]['policy_followed']) && $policies[$key]['policy_followed']){
                        $policies[$key]['exceptions_taken'] = [];
                    }
                    break;
                case 'foir':
                    $status = isset($application->creditReport) && isset($application->creditReport[0]) ? true : false;
                    if(isset($verificationList[$key]['status']) && !$verificationList[$key]['view']['Acceptable'] && isset($policies[$key]['exceptions_taken']) && $policies[$key]['exceptions_taken']){
                        $policies[$key]['policy_followed'] = [];
                        if($verificationList[$key]['view']['Errors']) {
                            $policies[$key]['exceptions_taken']['name'] = implode(',',$verificationList[$key]['view']['Errors']);
                        }
                    }elseif(isset($verificationList[$key]['status']) && isset($policies[$key]['policy_followed']) && $policies[$key]['policy_followed']){
                        $policies[$key]['exceptions_taken'] = [];
                    }

                    if(!$status){
                        $policies[$key]['exceptions_taken'] = [];
                        $policies[$key]['policy_followed'] = [];
                    }

                    break;
                case 'reference_taken':
                    if(isset($verificationList[$key]['status']) && !$verificationList[$key]['status'] && isset($policies[$key]['exceptions_taken']) && $policies[$key]['exceptions_taken']){
                        $policies[$key]['policy_followed'] = [];
                    }elseif(isset($verificationList[$key]['status']) && isset($policies[$key]['policy_followed']) && $policies[$key]['policy_followed']){
                        $policies[$key]['exceptions_taken'] = [];
                    }
                    break;
                case 'work_experience':
                    if(isset($verificationList[$key]['status']) && !$verificationList[$key]['view']['Acceptable'] && isset($policies[$key]['exceptions_taken']) && $policies[$key]['exceptions_taken']){
                        $policies[$key]['policy_followed'] = [];
                        if($verificationList[$key]['view']['Errors']) {
                            $policies[$key]['exceptions_taken']['name'] = implode(',',$verificationList[$key]['view']['Errors']);
                        }
                    }elseif(isset($verificationList[$key]['status']) && isset($policies[$key]['policy_followed']) && $policies[$key]['policy_followed']){
                        $policies[$key]['exceptions_taken'] = [];
                    }
                    break;
                case 'min_balance_charge':
                    if(isset($verificationList[$key]['status']) && $verificationList[$key]['view']['Acceptable'] && isset($policies[$key]['exceptions_taken']) && $policies[$key]['exceptions_taken']){
                        $policies[$key]['policy_followed'] = [];
                        if($verificationList[$key]['view']['Errors']) {
                            $policies[$key]['exceptions_taken']['name'] = implode(',',$verificationList[$key]['view']['Errors']);
                        }
                    }elseif(isset($verificationList[$key]['status'])){
                        $policies[$key]['exceptions_taken'] = [];
                    }
                    break;
                case 'personal_discussion_done':
                    if(isset($verificationList[$key]['status']) && isset($policies[$key]['policy_followed']) && $policies[$key]['policy_followed']){
                        $CallLogs = CallLogs::where('_id', $application->id)->where('id_type', 'application_id')->where('status', 'completed')->where('purpose', 'verification_call')->first(['id']);
                        $verificationList[$key]['status'] = isset($CallLogs->id) ? true : false;
                    }
                    break;
                case 'credit_score':
                    if(isset($verificationList[$key]['status']) && !$verificationList[$key]['view']['Acceptable'] && isset($policies[$key]['exceptions_taken']) && $policies[$key]['exceptions_taken']){
                        $policies[$key]['policy_followed'] = [];
                        if($verificationList[$key]['view']['Errors']) {
                            $policies[$key]['exceptions_taken']['name'] = implode(',',$verificationList[$key]['view']['Errors']);
                        }

                        if(trim($policies[$key]['exceptions_taken']['name']) == 'Credit Score is'){
                            $policies[$key]['exceptions_taken']['name'] = 'Credit Score is not available';
                        }

                    }elseif(isset($verificationList[$key]['status']) && isset($policies[$key]['policy_followed']) && $policies[$key]['policy_followed']){
                        $policies[$key]['exceptions_taken'] = [];
                    }
                    break;
                default:
                    if(isset($verificationList[$key]['status']) && $verificationList[$key]['status'] && isset($policies[$key]['exceptions_taken']) && $policies[$key]['exceptions_taken']){
                        $policies[$key]['policy_followed'] = [];
                    }elseif(isset($verificationList[$key]['status']) && isset($policies[$key]['policy_followed']) && $policies[$key]['policy_followed']){
                        $policies[$key]['exceptions_taken'] = [];
                    }
                    break;
            }
        }
        return $policies;
    }

    public function normalizePolicyData($policies){
        $data = [];
        foreach ($policies as $policy){
            if($policy['policy_followed']){
                $data['policy_followed'][] = $policy['policy_followed'];
            }
            if($policy['exceptions_taken']){
                $data['exceptions_taken'][] = $policy['exceptions_taken'];
            }
        }

        $view = [];
        if(isset($data['policy_followed'])) {
            foreach ($data['policy_followed'] as $key => $item) {
                $view[$key]['policy_followed'] = $item;
                $view[$key]['exceptions_taken'] = isset($data['exceptions_taken'][$key]) ? $data['exceptions_taken'][$key] : '';
            }
        }

        if(isset($data['exceptions_taken'])) {
            foreach ($data['exceptions_taken'] as $_key => $item) {
                if ($_key > $key) {
                    $view[$_key]['exceptions_taken'] = $item;
                    $view[$_key]['policy_followed'] = [];
                }
            }
        }


        foreach ($view as $key => $item){
            if(((isset($item['exceptions_taken']) && isset($item['exceptions_taken']['status']) && !is_bool($item['exceptions_taken']['status'])) || empty($item['exceptions_taken'])) && ((isset($item['policy_followed']) && !is_bool($item['policy_followed']['status'])) || empty($item['policy_followed']))){
                unset($view[$key]);
            }
        }

        return $view;
    }

    public function VerifyConsumerApplication($id)
    {
        $data = Input::all();
        if(count(json_decode($data['exception_doc_list']))){
            ConsumerApplicationElement::where('application_id',$id)->update(['multi_tranche_exception_list'=>$data['exception_doc_list']]);
        }else{
            ConsumerApplicationElement::where('application_id',$id)->update(['multi_tranche_exception_list'=>null]);
        }

        if(isset($data['next_status'])) {
            $applicationData = ConsumerApplication::where('id', $id)->where('state', strtolower($data['next_status']))->first();
            if (isset($applicationData->id)) {
                return \response()->json(['status' => 'FAIL', 'message' => 'There are some updates, redirecting to main page.', 'refresh' => true]);
            }
        }

        $segments = [];
        foreach ($data as $key => $item) {
            if (!in_array($key, ['having_list', '_token'])) {
                $segments[$key] = $item;
            }
        }

        $export = false;
        $_checklist = Checklist::where('application_id', $id)->first(['id']);
        $_acceptableDataReason = AcceptableDataReason::where('application_id', $id)->first(['id']);
        $application = ConsumerApplication::with(['application_element' => function ($query) {
            $query->select('application_id', 'installation_address_pincode');
        }])->find($id);

        if (isset($_acceptableDataReason->id)) {
            $acceptableDataReason = AcceptableDataReason::find($_acceptableDataReason->id);
        } else {
            $acceptableDataReason = new AcceptableDataReason();
            $acceptableDataReason->application_id = $id;
        }

        if (isset($_checklist->id)) {
            $checklist = Checklist::find($_checklist->id);
        } else {
            $checklist = new Checklist();
            $checklist->application_id = $id;
        }
        foreach (json_decode($data['having_list']) as $item) {
            if ($item->name == 'cpv[]') {
                $_key = 'cpv';
            } else {
                $_key = $item->name;
            }
            if (isset($segments[$_key])) {
                $this->updateVerificationCheckList($item, $id, $segments, $checklist, $application, $acceptableDataReason);
            }
        }
        $checklist->save();
        $acceptableDataReason->user_id = Auth::user()->id;
        $acceptableDataReason->save();

        if(Input::has('gen-camp-report')) {
            $this->generateCAMReport($id);
        }

        if (!Input::has('is_adviser')) {
            $status = $this->getArrayBackValidate($application->state);
            if (in_array('approved', $status)) {
                // sent to disbursed
                $_status = 'disbursed';
            } else {
                //sent to approved
                $_status = 'approved';
            }

            if (Input::has('is_waiting_for_decision')) {
                if ($_status == 'disbursed') {
                    $_status = 'disbursement checklist done';
                } else {
                    $_status = 'waiting for decision';
                }
            }

            if ($_status == 'waiting for decision') {
                $grade = new GradeController(new Request());
                $grade->ApprovalCheckV1($id);
                //(new Slack(new Request(['title' => 'Auto Decision - Ended', 'fields' => ['id' => $id, 'time' => Carbon::now()->toDateTimeString()], 'group' => Slack::$STAGE_TESTING])))->send();
                $grade->initAutoDocumentation($grade, $id);
            }

            return $this->updateApplicationStatus($id, $_status);
        }

        return \response()->json(['status' => 'OK'], 200);
//        if($export){
//            $response = ConsumerVerification::where('application_id',$id)->first();
//            $user = \App\ConsumerApplication::where('id', $id)->first();
//            $pdf = App::make('snappy.pdf.wrapper');
//            $html = view('admin.documents.verification_checklist',['verification'=>$response,'user'=>$user]);
//            $pdf->loadHTML($html)->setOption('encoding', 'UTF-8')->setPaper('a4')->setOrientation('portrait')->setOption('margin-bottom', 30);
//            $checklist = $pdf->setOption('footer-html', view('admin.editor.footer',['type'=>0])->render());
//            return $checklist->download('verification_checklist.pdf');
//        }
//
//        \Session::flash('success', 'Consumer Verification updated successfully');
//        return redirect()->back();
    }

    public function VerifyConsumerApplicationV1($id)
    {

        $data = Input::all();
        if(count(json_decode($data['exception_doc_list']))){
            ConsumerApplicationElement::where('application_id',$id)->update(['multi_tranche_exception_list'=>$data['exception_doc_list']]);
        }else{
            ConsumerApplicationElement::where('application_id',$id)->update(['multi_tranche_exception_list'=>null]);
        }

        if(isset($data['next_status'])) {
            $applicationData = ConsumerApplication::where('id', $id)->where('state', strtolower($data['next_status']))->first();
            if (isset($applicationData->id)) {
                return \response()->json(['status' => 'FAIL', 'message' => 'There are some updates, redirecting to main page.', 'refresh' => true]);
            }
        }
        if(isset($data['selected_risk_category'])){
            ConsumerApplicationElement::where('application_id',$id)->update(['risk_category'=>$data['selected_risk_category'],'verify_risk_category'=>1]);
            unset($data['selected_risk_category']);
        }

        $segments = [];
        foreach ($data as $key => $item) {
            if (!in_array($key, ['having_list', '_token'])) {
                $segments[$key] = $item;
            }
        }

        $export = false;
        $_checklist = Checklist::where('application_id', $id)->first(['id']);
        $_acceptableDataReason = AcceptableDataReason::where('application_id', $id)->first(['id']);
        $application = ConsumerApplication::with(['application_element' => function ($query) {
            $query->select('application_id', 'installation_address_pincode');
        }])->find($id);

        if (isset($_acceptableDataReason->id)) {
            $acceptableDataReason = AcceptableDataReason::find($_acceptableDataReason->id);
        } else {
            $acceptableDataReason = new AcceptableDataReason();
            $acceptableDataReason->application_id = $id;
        }

        if (isset($_checklist->id)) {
            $checklist = Checklist::find($_checklist->id);
        } else {
            $checklist = new Checklist();
            $checklist->application_id = $id;
        }
        foreach (json_decode($data['having_list']) as $item) {
            if ($item->name == 'cpv[]') {
                $_key = 'cpv';
            } else {
                $_key = $item->name;
            }
            if (isset($segments[$_key])) {
                $this->updateVerificationCheckList($item, $id, $segments, $checklist, $application, $acceptableDataReason);
            }
        }
        $checklist->save();
        $acceptableDataReason->user_id = Auth::user()->id;
        $acceptableDataReason->save();

        if (Input::has('bank_details_exception')  && Input::get('bank_details_exception') != ''){
            $checklistException = new ChecklistExceptionLogs();
            $checklistException->fill([
                'application_id'=> $id,
                'exception_type'=> 'bank_exception',
                'exception'     => Input::get('bank_details_exception'),
                'created_by'    => Auth::user()->id
            ]);
            $checklistException->save();
        }
        if (Input::has('mandate_amount_exception_remarks')  && Input::get('mandate_amount_exception_remarks') != ''){
            $checklistException = new ChecklistExceptionLogs();
            $checklistException->fill([
                'application_id'=> $id,
                'exception_type'=> 'mandate_amount_exception',
                'exception'     => Input::get('mandate_amount_exception_remarks'),
                'created_by'    => Auth::user()->id
            ]);
            $checklistException->save();
        }
        if (Input::has('mandate_document_exception_remarks')  && Input::get('mandate_document_exception_remarks') != ''){
            $checklistException = new ChecklistExceptionLogs();
            $checklistException->fill([
                'application_id'=> $id,
                'exception_type'=> 'mandate_document_exception',
                'exception'     => Input::get('mandate_document_exception_remarks'),
                'created_by'    => Auth::user()->id
            ]);
            $checklistException->save();
        }

        if(Input::has('gen-camp-report')) {
            $this->generateCAMReport($id);
        }

        if (!Input::has('is_adviser')) {
            $status = $this->getArrayBackValidate($application->state);
            if (in_array('approved', $status)) {
                // sent to disbursed
                $_status = 'disbursed';
            } else {
                //sent to approved
                $_status = 'approved';
            }

            if (Input::has('is_waiting_for_decision')) {
                if ($_status == 'disbursed') {
                    $_status = 'disbursement checklist done';
                } else {
                    $_status = 'waiting for decision';
                }
            }

            if ($_status == 'waiting for decision') {
                $grade = new GradeController(new Request());
                $grade->ApprovalCheckV1($id);
                //(new Slack(new Request(['title' => 'Auto Decision - Ended', 'fields' => ['id' => $id, 'time' => Carbon::now()->toDateTimeString()], 'group' => Slack::$STAGE_TESTING])))->send();
                $grade->initAutoDocumentation($grade, $id);
            }

            return $this->updateApplicationStatus($id, $_status);
        }



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

    public function getSubventionDetails($application, $includeTrancheDisbursement = true){
        $charge_subvention_remaining_amount = $application->merchant && $application->merchant->charge_subvention_remaining_amount ? 1 : 0;
        $downPayment = 0;
        if($charge_subvention_remaining_amount){
            $downPayment = $application->emi->upfront_from_customer;
        }
        $subvention_amount = (($application->approved_amount - $downPayment)*$application->emi->subvention)/100;

        if($includeTrancheDisbursement) {
            $multiStageDisbursement = (new MultiStageDisbursement())->getSubventionInvoiceAmount($application, $subvention_amount, true);
            $subvention_amount = $multiStageDisbursement['subvention_amount'] ?? $multiStageDisbursement;
        }

        if ($subvention_amount) {
            $gstDetailsSubvention = (new ConsumerDocument(new Request()))->getGSTDetails(
                [
                    'amount' => $subvention_amount,
                    'state' => $application->merchant->state
                ]
                ,0);

            $subventionWithGST = $gstDetailsSubvention[0]['net_amount'];
            $GST = 0;
            foreach ($gstDetailsSubvention as $item){
                $subventionWithGST += $item['gst_amount'];
                $GST += $item['gst_amount'];
            }

            return ['WithGST' => round($subventionWithGST), 'Net' => $gstDetailsSubvention[0]['net_amount'], 'GST' => $GST, 'gstDetailsSubvention' => $gstDetailsSubvention];
        }

        return ['WithGST' => 0, 'Net' => 0, 'GST' => 0];
    }

    public function getDocumentByEmpType(Request $request)
    {
        $options = '<option value="">Select Set</option>';
        if ($request->has('type')) {
            $data = DocumentSets::where('employment_type', str_replace(' ', '_', strtolower($request->get('type'))))->get(['id', 'name']);
            foreach ($data as $item) {
                $options .= '<option value="' . $item->id . '">' . $item->name . '</option>';
            }
        }

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

    public function applicationActivationLink($id)
    {

        $mandate = Mandate::where('consumer_application_id', $id)->first();
        if (isset($mandate->mandate_id)) {
            $user = \App\ConsumerApplication::with('bank_details', 'merchant')->where('id', $id)
                ->first();

            if (!isset($user->bank_details->bank_name)) {
                \Session::flash('error', 'Bank is not linked!');
                return redirect()->back();
            }
            if (!isset($user->merchant->merchant_name)) {
                \Session::flash('error', 'Merchant is not linked!');
                return redirect()->back();
            }

            $mandateData = [
                'link' => $mandate->mandate_id,
                'name' => $user->name,
                'bank_details' => $user->bank_details,
                'mandate' => $mandate,
                'merchant' => $user->merchant,
                'disclaimer' => 1
            ];

            $response = ['to' => $user->email, 'subject' => 'E-NACH Registration'];
            $consent_key = array_search ('E-nach', CommunicationService::$com_category);
            $email_comm = CommunicationMapping::whereRaw('FIND_IN_SET('.$consent_key.',type_ids)')->where('communication_id',1)->where('merchant_id',$user->merchant->id)->count();
            $communication = CommunicationMapping::where('merchant_id',$user->merchant->id)->count();
            if($email_comm == 1 || $communication == 0 || $consent_key == 0) {
                \Mail::send('emails.consumer_activation_mail', [
                    'data' => $mandateData
                ], function ($message) use ($response) {
                    $message->to($response['to'])->subject($response['subject']);
                    $message->cc(_env('NOTIFY_EMAIL', ''));
                });
            }

            //SMS notification
            $message = "Dear " . $user->name . ", To finalise your Easy EMI plan please register the auto-debit mandate by clicking on " . $mandateData['link'] . ".  You will require your Aadhaar ID and Mobile Phone to complete this process. In case you face any issues, please call us on +91-99672 35047.<br/>Best Regards,<br/>Team Credit Fair";
            $entity = ['templateid' => '1307159974211579966', 'entityid' => Templates::$entityid];

            $mobile_number = '91' . $user->mobile_number;
            $sm_comm = CommunicationMapping::whereRaw('FIND_IN_SET('.$consent_key.',type_ids)')->where('communication_id',2)->where('merchant_id',$user->merchant->id)->count();
            if($sm_comm == 1 || $communication == 0 || $consent_key == 0) {
                send_sms($mobile_number, ['message' => $message, 'id' => $id, 'id_type' => 'application_id', 'templateDetails' => $entity]);
            }
            \Session::flash('success', 'Activation link successfully sent!');
        } else {
            \Session::flash('error', 'Failed to generate activation link - Activation link is not added!');
        }
        return redirect()->back();
    }

    public function sendDisbursementRequest($id)
    {
        try{
            $application = ConsumerApplication::find($id);
            $offer_id = $application->offer_id;
            $disbursementOffers = DisbursementOffers::with('disbursementLogs')->where('application_id', $id)->where('offer_id', $offer_id)->orderBy('phase','asc')->get();
            $total_phases = count($disbursementOffers);
            for($i=0;$i<count($disbursementOffers);$i++){

                if(!empty($disbursementOffers[$i]->id)){

                    if(isset($disbursementOffers[$i]['disbursementLogs']) && count($disbursementOffers[$i]['disbursementLogs']) > 0){
                        continue;
                    }else{
                        $phase = $disbursementOffers[$i]->phase;
                        $isAlreadyRequested = DisbursementRequests::where('application_id',$id)->where('phase',$phase)->whereNull('deleted_at')->first();
                        if (isset($isAlreadyRequested->id)){
                            \Session::flash('error', 'One Request already pending for this phase');
                            return redirect()->back();
                        }
                        $request = new Request(['id' => $id]);

                        $application = ConsumerApplication::with('merchant', 'application_element', 'application_element.merchant_center','emi','emi.offer','offer','proFormaInvoice','invoice')->where('id', $id)->first(['id', 'merchant_id','name','approved_amount','offer_id','applicant_id','lender_id','co_applicant_name','purpose']);
                        if (isset($application->id)) {
                            $data['disbursement_data'] = $this->getDisbursementSummary($request, $application);
                        }
                        if (isset($data["disbursement_data"]["net_disbursement"]["disbursement_amount"])) {
                            $amount = $data["disbursement_data"]["net_disbursement"]["disbursement_amount"];
                        }else{
                            (new Slack(new Request(['title' => 'Disbursement Request Error', 'fields' => ['error' => 'disbursement_amount key not found', 'id' => $id], 'group' => Slack::$STAGE_TESTING])))->send();
                            \Session::flash('error', 'Something went wrong');
                            return redirect()->back();
                        }
                        break;
                    }

                }
            }
            $data = [
                'application_id' => $id,
                'requested_by' => Auth::user()->id,
                'phase' => $phase,
                'amount' => $amount,
                'request_date' => Carbon::now()->toDateTimeString(),
                'created_at' => Carbon::now()->toDateTimeString(),
                'updated_at' => Carbon::now()->toDateTimeString()
            ];
            DisbursementRequests::insert($data);
        }catch (\Exception $e){
            (new Slack(new Request(['title' => 'Disbursement Request Error', 'fields' => ['e' => $e->getMessage(),'l' => $e->getLine(),'t' => $e->getTraceAsString(), 'id' => $id], 'group' => Slack::$STAGE_TESTING])))->send();
            \Session::flash('error', 'Something went wrong');
            return redirect()->back();
        }

        \Session::flash('success', 'Next Phase Disbursement request added');
        return redirect()->back();
    }

    public function renderAppSummary($id){
        $applicantSummary = ConsumerApplication::with('abflUTR','avanseUTRStatus','application_element','CFPayoutDirectTransfer','comment','documents','checkmandate')->find($id);
        $summary = [];
        if(isset($applicantSummary)){
            if(in_array($applicantSummary->state,['ready for disbursement','disbursed'])){
                $appkyc = 1;
                if(isset($applicantSummary->co_applicant_id)){
                    $coappkyc = 1;
                }
            }

            $KYCDetails = KYCDetails::where('application_id', $applicantSummary->id)->whereNotNull('response')->get();
            $appkyc = null;
            $coappkyc = null;
            if(isset($KYCDetails[0]) && $KYCDetails[0]->applicant_type == 1){
                $appkyc = 1;
            }else if(isset($KYCDetails[1]) && $KYCDetails[1]->applicant_type == 1){
                $appkyc = 1;
            }
            if(isset($KYCDetails[0]) && $KYCDetails[0]->applicant_type == 2){
                $coappkyc = 1;
            }else if(isset($KYCDetails[1]) && $KYCDetails[1]->applicant_type == 2){
                $coappkyc = 1;
            }

            if(ConsumerApplication::checkKarzaApproved($applicantSummary->id,1)){
                $appkyc = 1;
            }
            if(ConsumerApplication::checkKarzaApproved($applicantSummary->id,2)){
                $coappkyc = 1;
            }

            $name = trim($applicantSummary->name);
            $parts = explode(' ', $name);
            if(count($parts) === 1){
                $firstname = $parts[0];
            }else if (count($parts) === 2) {
                list($firstname, $lastname) = $parts;
            } else if (count($parts) === 3) {
                list($firstname, $middlename, $lastname) = $parts;
            } else if(count($parts) === 4){
                $firstname = $parts[0];
                $middlename = $parts[1].' '.$parts[2];
                $lastname = $parts[3];
            }else if(count($parts) > 4){
                // // $array = array_map(create_function('$a', 'return implode(" ", $a);'), array_chunk(preg_split('/\s+/', $name), ceil(count($parts)/3)));
                // $array = array_map(function($a){return implode(" ", $a);}, array_chunk(preg_split('/\s+/', $name), ceil(count($parts)/3)));
                $firstname = $parts[0];
                $middlename = $parts[1];
                $lastname = $parts[count($parts)-1];
            }
            $summary[$id]['first_name'] = isset($firstname) ? 1 : null;
            $summary[$id]['last_name'] = isset($lastname) ? 1 : null;
            $summary[$id]['dob'] = isset($applicantSummary->dob) ? 1 : null;
            $summary[$id]['pan_number'] = isset($applicantSummary->pan_card) ? 1 : null;
            $summary[$id]['email'] = isset($applicantSummary->email) ? 1 : null;
            $summary[$id]['mobile'] = isset($applicantSummary->mobile_number) ? 1 : null;
            $summary[$id]['profession'] = isset($applicantSummary->employee_status) ? 1 : null;
            $summary[$id]['income'] = isset($applicantSummary->monthly_income) ? 1 : null;
            $address = trim($applicantSummary->current_address_line_1." ".$applicantSummary->current_address_landmark." ".$applicantSummary->current_address_city." ".$applicantSummary->current_address_state);
            $summary[$id]['current_address'] = !empty($address) ? 1 : null;
            $summary[$id]['pincode'] = isset($applicantSummary->current_address_pincode) ? 1 : null;
            $summary[$id]['loan_amount'] = isset($applicantSummary->loan_amount) ? 1 : null;
            $summary[$id]['app_state'] = $applicantSummary->state;
            
            $summary[$id]['pan_card_doc'] = null;
            $summary[$id]['aadhaar_card_doc'] = null;
            $summary[$id]['current_address_proof_doc'] = null;

            $summary[$id]['income_status'] = null;
            if(isset($applicantSummary->employee_status)){
                $summary[$id]['income_status'] = $applicantSummary->employee_status;
                switch($applicantSummary->employee_status){
                    case 'UNEMPLOYED':
                        $summary[$id]['coapp_income_proof_doc'] = null;
                        break;
                    case 'SALARIED':
                        $summary[$id]['salary_slip_doc'] = null;
                        $summary[$id]['bank_statement_doc'] = null;
                        $summary[$id]['salary_certificate_doc'] = null;
                        $summary[$id]['itr_doc'] = null;
                        $summary[$id]['offer_letter_doc'] = null;
                        break;
                    case 'BUSINESS':
                        $summary[$id]['gst_doc'] = null;
                        $summary[$id]['shopact_doc'] = null;
                        $summary[$id]['udyog_aadhaar_doc'] = null;
                        $summary[$id]['registration_certificate_doc'] = null;
                        $summary[$id]['itr_doc'] = null;
                        break;
                    case 'Self Employed - Business':
                        $summary[$id]['salary_certificate_doc'] = null;
                        $summary[$id]['shopact_doc'] = null;
                        $summary[$id]['registration_certificate_doc'] = null;
                        $summary[$id]['itr_doc'] = null;
                        break;
                    case 'Self Employed - Professional':
                        $summary[$id]['license_doc'] = null;
                        $summary[$id]['itr_doc'] = null;
                        $summary[$id]['bank_statement_doc'] = null;
                        $summary[$id]['professional_certificate_doc'] = null;
                        break;
                    case 'PENSIONER':
                        $summary[$id]['pension_credit_bank_statement_doc'] = null;
                        $summary[$id]['pension_certificate_doc'] = null;
                        break;
                    case 'HOUSEWIFE':
                        $summary[$id]['utility_bill_doc'] = null;
                        $summary[$id]['property_tax_doc'] = null;
                        break;
                }
            }

            if($applicantSummary->lender_id == ConsumerApplication::AVANSE_LENDER_ID){
                $esign = LoanAgreementVendor::where('application_id',$id)->where('status','com')->first();
                if(isset($esign->id)){
                    if($esign->is_bor_signed == 1){
                        $aesign = 1;
                    }
                    if($esign->is_cobor_signed == 1){
                        $caesign = 1;
                    }
                }
                if(isset($aesign) || isset($caesign)){
                    $avesign = 1;
                }
            }

            $digital = DigitalSignDetails::where('application_id',$applicantSummary->id)->where('type','=','consumer')->get();
            if(count($digital)){
                foreach($digital as $appSign){
                    if($appSign->applicant == 1){
                        $adsign = 1;
                    }
                    if($appSign->applicant == 2){
                        $cadsign = 1;
                    }
                }
                if(isset($adsign) || isset($cadsign)){
                    $dsign = 1;
                }
            }
 
            $summary[$id]['decision_kyc_applicant'] = $appkyc;
            $summary[$id]['decision_kyc_coapplicant'] = $coappkyc;
            $summary[$id]['decision_quotation'] = null;
            $summary[$id]['decision_signed_proforma'] = null;
            $summary[$id]['decision_nach'] = isset($applicantSummary->checkmandate) ? 1 : null;
            $summary[$id]['decision_esign'] = isset($avesign) ? 1 : (isset($dsign) ? 1 : null);
            if(isset($applicantSummary->documents)){
                foreach($applicantSummary->documents as $doc){
                    if(stripos($doc->file_type,'pan_card') !== false){
                        $summary[$id]['pan_card_doc'] = 1;
                    }
                    if((strpos($doc->file_type,'aadhar_card') !== false) || (stripos($doc->file_type,'aadhaar_card') !== false)){
                        $summary[$id]['aadhaar_card_doc'] = 1;
                    }
                    if(stripos($doc->file_type,'current_address') !== false){
                        $summary[$id]['current_address_proof_doc'] = 1;
                    }
                    if(isset($applicantSummary->employee_status)){
                        $summary[$id]['income_status'] = $applicantSummary->employee_status;
                        switch($applicantSummary->employee_status){
                            case 'UNEMPLOYED':
                                if(stripos($doc->file_type,'Co-applicant with income proof') !== false){
                                    $summary[$id]['coapp_income_proof_doc'] = 1;
                                }
                                break;
                            case 'SALARIED':
                                if(stripos($doc->file_type,'salary_slip') !== false || stripos($doc->file_type,'3_months_salary_slip') !== false){
                                    $summary[$id]['salary_slip_doc'] = 1;
                                }
                                if(stripos($doc->file_type,'bank_statement') !== false){
                                    $summary[$id]['bank_statement_doc'] = 1;
                                }
                                if(stripos($doc->file_type,'salary_certificate') !== false){
                                    $summary[$id]['salary_certificate_doc'] = 1;
                                }
                                if(stripos($doc->file_type,'itr') !== false){
                                    $summary[$id]['itr_doc'] = 1;
                                }
                                if(stripos($doc->file_type,'offer') !== false || stripos($doc->file_type,'offer_letter') !== false){
                                    $summary[$id]['offer_letter_doc'] = 1;
                                }
                                break;
                            case 'BUSINESS':
                                if(strpos($doc->file_type,'gst') !== false || stripos($doc->file_type,'gst_certificate') !== false){
                                    $summary[$id]['gst_doc'] = 1;
                                }
                                if(stripos($doc->file_type,'shop') !== false){
                                    $summary[$id]['shopact_doc'] = 1;
                                }
                                if(stripos($doc->file_type,'udyog') !== false){
                                    $summary[$id]['udyog_aadhaar_doc'] = 1;
                                }
                                if(stripos($doc->file_type,'registration') !== false || stripos($doc->file_type,'registration_certificate') !== false){
                                    $summary[$id]['registration_certificate_doc'] = 1;
                                }
                                if(stripos($doc->file_type,'itr') !== false){
                                    $summary[$id]['itr_doc'] = 1;
                                }
                                break;
                            case 'Self Employed - Business':
                                if(stripos($doc->file_type,'salary_certificate') !== false){
                                    $summary[$id]['salary_certificate_doc'] = 1;
                                }
                                if(stripos($doc->file_type,'shop') !== false){
                                    $summary[$id]['shopact_doc'] = 1;
                                }
                                if(stripos($doc->file_type,'registration') !== false || stripos($doc->file_type,'registration_certificate') !== false){
                                    $summary[$id]['registration_certificate_doc'] = 1;
                                }
                                if(stripos($doc->file_type,'itr') !== false){
                                    $summary[$id]['itr_doc'] = 1;
                                }
                                break;
                            case 'Self Employed - Professional':
                                if(stripos($doc->file_type,'license')){
                                    $summary[$id]['license_doc'] = 1;
                                }
                                if(stripos($doc->file_type,'itr') !== false){
                                    $summary[$id]['itr_doc'] = 1;
                                }
                                if(stripos($doc->file_type,'bank_statement') !== false){
                                    $summary[$id]['bank_statement_doc'] = 1;
                                }
                                if(stripos($doc->file_type,'professional_certificate') !== false){
                                    $summary[$id]['professional_certificate_doc'] = 1;
                                }
                                break;
                            case 'PENSIONER':
                                if(stripos($doc->file_type,'pension_credit_bank_statement') !== false || stripos($doc->file_type,'bank_statement') !== false){
                                    $summary[$id]['pension_credit_bank_statement_doc'] = 1;
                                }
                                if(stripos($doc->file_type,'pension_certificate') !== false){
                                    $summary[$id]['pension_certificate_doc'] = 1;
                                }
                                break;
                            case 'HOUSEWIFE':
                                if(stripos($doc->file_type,'utility_bill')){
                                    $summary[$id]['utility_bill_doc'] = 1;
                                }
                                if(stripos($doc->file_type,'property_tax')){
                                    $summary[$id]['property_tax_doc'] = 1;
                                }
                                break;
                        }
                    }
                    // if(strpos($doc->file_type,'digio report applicant') !== false){
                    //     $summary[$id]['decision_kyc_applicant'] = 1;
                    // }
                    // if(strpos($doc->file_type,'digio report coapplicant') !== false){
                    //     $summary[$id]['decision_kyc_coapplicant'] = 1;
                    // }
                    if((stripos($doc->file_type,'quotation') !== false) || (stripos($doc->file_type,'invoice bill') !== false) || (stripos($doc->file_type,'proforma') !== false)){
                        $summary[$id]['decision_quotation'] = 1;
                    }
                    if(stripos($doc->file_type,'pro_forma_invoice') !== false){
                        $summary[$id]['decision_signed_proforma'] = 1;
                    }
                    // if((stripos($doc->file_type,'nach') !== false) || (stripos($doc->file_type,'mandate') !== false)){
                    //     $summary[$id]['decision_nach'] = 1;
                    // }
                    if((strpos($doc->file_type,'loan_agreement_esign') !== false) || (strpos($doc->file_type,'agreement') !== false)){
                        $summary[$id]['decision_esign'] = 1;
                    }
                }
            }

            $comment = '';
            $shortRemark = '';
            foreach($applicantSummary->comment as $remark){
                if($applicantSummary->state == 'rejected'){
                    $comment = trim(str_replace('Rejection Reason:','',$remark->comment));
                    switch ($comment) {
                        case 'Not enough credit history':
                            $shortRemark = 'Thin Credit';
                            break;
                        case 'Overdues in Active loans':
                            $shortRemark = 'Overdues in loans';
                            break;
                        case 'High DPDs':
                            $shortRemark = 'High DPDs';
                            break;
                        case 'WOF/PWOS/SET/SF/DBT Loans':
                            $shortRemark = 'WOF/SF/SET/DBT Loans';
                            break;
                        case 'ECS/Cheque Bounces':
                            $shortRemark = 'ECS Bounces';
                            break;
                        case 'Low Average Bank Balance':
                            $shortRemark = 'Low ABB';
                            break;
                        case 'Too Many Active Loans':
                            $shortRemark = 'Too Many Active Loans';
                            break;
                        case 'Income Insufficient':
                            $shortRemark = 'Insufficient Income';
                            break;
                        case 'ECS/Cheque Bounces':
                            $shortRemark = 'ECS Bounces';
                            break;
                        case 'Low Credit Score':
                            $shortRemark = 'Low Credit Score';
                            break;
                        case 'Unemployed':
                            $shortRemark = 'Unemployed';
                            break;
                        case 'Co-applicant’s Repayment history is negative':
                            $shortRemark = 'Co-app repayment issue';
                            break;
                        default:
                            $shortRemark = $comment;
                            break;
                    }
                }
                if($applicantSummary->state == 'aborted'){
                    $comment = trim(str_replace('Abort Reason:','',$remark->comment));
                    switch ($comment) {
                        case 'Customer opted for cash payment':
                            $shortRemark = 'Opted for cash payment';
                            break;
                        case 'Customer is not interested in taking the loan':
                            $shortRemark = 'Not interested for loan';
                            break;
                        case 'Customer is not comfortable with the EMI plans offered':
                            $shortRemark = 'EMI plan issues';
                            break;
                        case 'Customer is not responding for additional documents':
                            $shortRemark = 'No response';
                            break;
                        case 'Customer is not purchasing the product':
                            $shortRemark = 'Requirement dropped';
                            break;
                        case 'Customer has postponed taking the loan':
                            $shortRemark = 'Requirement dropped';
                            break;
                        case 'Customer not happy with the service':
                            $shortRemark = 'Unsatisfactory service';
                            break;
                        case 'Demo login':
                            $shortRemark = 'Test lead';
                            break;
                        default:
                            $shortRemark = $comment;
                            break;
                    }
                }
                $summary[$id]['reason'] = $shortRemark;
            }
            
            $av_transactionRef = '';
            if(isset($applicantSummary->avanseUTRStatus)){
                $avanseUTRStatusResponse = json_decode($applicantSummary->avanseUTRStatus->response);
                foreach ($avanseUTRStatusResponse->disbResponse as $disbResponse){
                    $av_transactionRef = $disbResponse->transactionRef ?? '';
                }
            }
            if(empty($av_transactionRef)){
                if(isset($applicantSummary->CFPayoutDirectTransfer)){
                    foreach($applicantSummary->CFPayoutDirectTransfer as $cfpayout){
                        $av_transactionRef = $cfpayout->utr ?? '';
                    }
                }
            }
            if(empty($av_transactionRef)){
                if(isset($applicantSummary->abflUTR)){
                    foreach($applicantSummary->abflUTR as $abfl){
                        $av_transactionRef = $abfl->utr ?? '';
                    }
                }
            }
            $summary[$id]['disbursement_utr'] = $applicantSummary->application_element->reference_number ? $applicantSummary->application_element->reference_number : $av_transactionRef;
        }
        return response()->json(['status' => 'OK', 'summary' => $summary], 200);
    }

    public function createBankDetails($id)
    {
        $data['consumer_application'] = ConsumerApplication::with('bank_details_multiple')->find($id);
        //echo "<pre>";print_r($data['consumer_application']);die;
        $data['sidebar'] = 'consumer-applications';
        //$data['users']             = User::all();
        //$data['merchants']         = Merchant::all();
        //$data['merchant_location'] = MerchantLocation::all();
        foreach($data['consumer_application']->bank_details_multiple as $value){
            if($value->applicant_type == 1){
                $data['consumer_application']->applicant_bank = $value;
            }
            if($value->applicant_type == 2){
                $data['consumer_application']->co_applicant_bank = $value;
            }
        }
        $data['application_status'] = $this->status;
        $data['consumer_application_id'] = $id;
        $data['show_mandate_creation'] = (new ConsumerApplicationController())->statusreversearray['approved'];
        $data['supported_bank'] = (new NachSupportedBank())->getBankLists(false);
        $data['account_aggregator'] = AccountAggregatorModel::where('application_id', $id)->where('is_monitoring', 1)->first(['id', 'is_monitoring']);
        return view('admin.consumer-application.bank.add', $data);
    }


    public function getTemplateReminders($communication_id, $application_id = 0, $consumerEmi = array())
    {
        $view = [];
        $application_id = ($application_id) ? $application_id : (Input::get('consumer_application_id') ? Input::get('consumer_application_id') : 0);
        if ($communication_id > 0) {
            $data = $this->getDetails($application_id);
            switch ($communication_id) {
                case Input::get('text') == 'rejected':
                    unset($data['disclaimer']);
                    $data['loan_amount_'] = isset($data['loan_amount']) && $data['loan_amount'] > 0 ? $data['loan_amount'] : (isset($data['loan_amount_']) ? $data['loan_amount_'] : '');
                    $view['body'] = view('emails.customer_loan_reject', ['data' => $data])->render();
                    $view['subject'] = 'Thanks for your loan application';
                    $view['sms'] = 'Dear ' . $data['name'] . ',  We regret to inform you that your loan application on Credit Fair is declined. You can re-apply with us after 3 months.<br/>Regards,<br/>Team Credit Fair';
                    $view['templateDetails'] = ['templateid' => '1307161744263324726', 'entityid' => Templates::$entityid];
                    $view['templateId'] = Templates::$rejected_customer;
                    $view['args'] = [$data['name'], $data['loan_amount_']];
                    break;
                case 1:
                    $view['body'] = view('emails.reminders.document_submission', ['data' => $data])->render();
                    $view['subject'] = 'Gentle reminder for Loan Documents';
                    break;
                case 2:
                    $view['body'] = view('emails.reminders.pre_approval_email', ['data' => $data])->render();
                    $view['subject'] = 'You have been pre-approved by Credit Fair!';
                    break;
                case 3:
                    $view['body'] = view('emails.reminders.document_submission', ['data' => $data])->render();
                    $view['subject'] = 'You have been pre-approved by Credit Fair!';
                    break;
                case 4:
                    $view['body'] = view('emails.reminders.document_received', ['data' => $data])->render();
                    $view['subject'] = 'We have received your documents';
                    break;
                case 5:
                    if (!isset($data['bank']->bank_name) && $data['mandate'] == 1) {
                        $view['error'] = 'Please add bank details';
                        break;
                    } else if (!isset($data['proFormaInvoice']->id)) {
                        $view['error'] = 'Please add Disbursement Advice';
                        break;
                    }
                    setlocale(LC_MONETARY, 'en_IN.UTF-8');

                    $loan_application_no = isset($data['proFormaInvoice']->loan_application_no) && !empty($data['proFormaInvoice']->loan_application_no) ? $data['proFormaInvoice']->loan_application_no : '';
                    if ($loan_application_no) {
                        if($data['lender_id'] == AvanseServices::$lender_id) {
                            $data['bank-details'] = [
                                'Beneficiary account number' => '918020009293418',
                                'Beneficiary name' => 'Avanse Financial Services Ltd',
                                'IFSC code' => 'UTIB0000028',
                                'Bank Name' => 'Axis Bank'
                            ];
                        }else if($data['lender_id'] == Lendbox::$lender_id || $data['lender_id'] == LendboxLSP::$lender_id){
                            $data['bank-details'] = [
                                'Beneficiary account number' => '000705047644',
                                'Beneficiary name' => 'Transactree Technologies Private Limited',
                                'IFSC code' => 'ICIC0000007',
                                'Bank Name' => 'ICICI BANK LTD'
                            ];
                        }else if($data['lender_id'] == Services::$lender_id){
                            $data['bank-details'] = [
                                'Beneficiary account number' => '200999509663',
                                'Beneficiary name' => 'Aditya Birla Finance LTD',
                                'IFSC code' => 'INDB0000001',
                                'Bank Name' => 'INDUSIND BANK LTD'
                            ];
                        }else if($data['lender_id'] == KMGP2P::$lender_id){
                            $data['bank-details'] = [
                                'Beneficiary account number' => '409002234039',
                                'Beneficiary name' => 'K M GLOBAL P2P FINANCE PRIVATE LIMITED COLLECTION ACCOUNT',
                                'IFSC code' => 'RATN0000088',
                                'Bank Name' => 'RBL Bank'
                            ];
                        }else if($data['lender_id'] == BlackSoil::$lender_id){
                            $data['bank-details'] = [
                                'Beneficiary account number' => '10245910063',
                                'Beneficiary name' => 'Blacksoil Capital Private Limited',
                                'IFSC code' => 'IDFB0040101',
                                'Bank Name' => 'IDFC First Bank'
                            ];
                        }else {
                            $data['bank-details'] = [
                                'Beneficiary account number' => '10245910063',
                                'Beneficiary name' => 'BLACKSOIL CAPITAL PRIVATE LIMITED',
                                'IFSC code' => 'IDFB0040101',
                                'Bank Name' => 'IDFC FIRST Bank'
                            ];
                        }
                    }

                    $processing_fee_amt = 0;

                    $applicationEMICalculation = ApplicationEMICalculation::where('application_id', $application_id)->first(['processing_fee']);
                    if (isset($applicationEMICalculation->processing_fee) && $applicationEMICalculation->processing_fee > 0) {
                        $paymentT = PaymentTransaction::where('application_id', $application_id)->where('payment_for', 'processing_fee')->where('refunded_at')->first(['id']);
                        $processing_fee_amt = !isset($paymentT->id) ? $applicationEMICalculation->processing_fee : 0;
                        if ($processing_fee_amt) {
                            $ConsumerApplicationFilesData = ConsumerApplicationFiles::where('consumer_application_id', $application_id)->where('file_type', 'processing_fee_receipt')->whereNull('deleted_at')->first(['id']);
                            $processing_fee_amt = !isset($ConsumerApplicationFilesData->id) ? $applicationEMICalculation->processing_fee : 0;
                        }
                    }

                    $emiPayments = EmiPayment::where('application_id', $application_id)->where('emi_date', $consumerEmi->emi_date)->where('payment_status', 'pending')->limit(1)->get();

                    if($emiPayments && $emiPayments[0]->pre_emi_amount > 0) {
                        if($emiPayments[0]->pre_emi_amount > 0 && $emiPayments[0]->emi_amount > 0) {
                            $this->sendPreEMICommunication($data, $consumerEmi, $processing_fee_amt, $application_id, $emiPayments, true);
                            break;
                        }else{
                            $this->sendPreEMICommunication($data, $consumerEmi, $processing_fee_amt, $application_id, $emiPayments, false);
                            break;
                        }
                    }

                    if ($data['mandate'] == 1) {
                        $view['body'] = view('emails.reminders.emi_due_reminder', ['data' => $data, 'consumerEmi' => $consumerEmi, 'processing_fee_amt' => $processing_fee_amt])->render();
                        $view['subject'] = 'EMI of Rs ' . (isset($consumerEmi->amount) ? money_format('%!i', $consumerEmi->amount + $processing_fee_amt) : '___________') . ' due on ' . (isset($consumerEmi->emi_date) ? date('d M, Y', strtotime($consumerEmi->emi_date)) : '___________');
                        $message = 'Dear ' . $data['name'] . ',<br/>EMI of Rs ' . (isset($consumerEmi->amount) ? money_format('%!i', $consumerEmi->amount + $processing_fee_amt) : '______________') . ' will be debited on ' . (isset($consumerEmi->emi_date) ? date('d M, Y', strtotime($consumerEmi->emi_date)) : '______________') . ' for your loan application no. ' . (isset($data['proFormaInvoice']->loan_application_no) ? $data['proFormaInvoice']->loan_application_no : '______________') . '. Please ensure balance in your ' . $data['bank']->bank_name . ' account number ending with ' . str_repeat('X', strlen(substr($data['bank']->account_number, 0, -4))) . substr($data['bank']->account_number, -4) . ' at least one day before.<br/>Please note that it would take 3 working days to update payment in our system post debit from your account. <br/>Best Regards,<br/>Team Credit Fair';
                        $view['templateDetails'] = ['templateid' => '1307166616369261282', 'entityid' => Templates::$entityid];
                        //$view['templateId'] = Templates::$nach;
                        //$view['args'] = [$data['name'], (isset($consumerEmi->amount) ? money_format('%!i', $consumerEmi->amount) : '______________'), (isset($consumerEmi->emi_date) ? date('d M, Y', strtotime($consumerEmi->emi_date)) : '______________'), (isset($data['proFormaInvoice']->loan_application_no) ? $data['proFormaInvoice']->loan_application_no : '______________'), $data['bank']->bank_name, str_repeat('X', strlen(substr($data['bank']->account_number, 0, -4))) . substr($data['bank']->account_number, -4)];

                    } else {

                        $razorpaydata['amount'] = $consumerEmi->amount + $processing_fee_amt;
                        $razorpaydata['email'] = "";
                        $razorpaydata['lender_id'] = $data['lender_id'];
                        $razorpaydata['id'] = $application_id;
                        $razorpaydata['purpose'] = 'emi';
                        if($processing_fee_amt > 0){
                            $razorpaydata['purpose'] = 'emi_and_processing_fee';
                        }
                        $razorpaydata['emi_date'] = $consumerEmi->emi_date;
                        $rajorpay_link = $this->getrazorpaylink($razorpaydata);
                        // $rajorpay_link = "";
//                        $hashids = new Hashids('Creditfair by CS', 20);
//                        $hashed_id = $hashids->encode($application_id);
//                        //$amount_hash = $hashids->encode($consumerEmi->amount);
//                        $amount_hash = base64_encode(wall_encrypt($consumerEmi->amount));
//
//                        $rajorpay_link = asset("paytm/" . $hashed_id . "?data=" . $amount_hash);
                        //$rajorpay_link = \Bitly::getUrl(asset("paytm/".$hashed_id));
//                        try{
//
//                            $rajorpay_link = \Bitly::getUrl($rajorpay_link);
//                        }catch (\Exception $e) {
//                        }

                        $view['body'] = view('emails.reminders.emi_due_reminder_with_payment_link', ['data' => $data, 'consumerEmi' => $consumerEmi, 'rajorpay_link' => $rajorpay_link, 'processing_fee_amt' => $processing_fee_amt])->render();
                        $view['subject'] = 'EMI of Rs ' . (isset($consumerEmi->amount) ? money_format('%!i', $consumerEmi->amount + $processing_fee_amt) : '___________') . ' due on ' . (isset($consumerEmi->emi_date) ? date('d M, Y', strtotime($consumerEmi->emi_date)) : '___________');
                        $message = 'Dear ' . $data['name'] . ',<br/>An installment  of Rs ' . (isset($consumerEmi->amount) ? money_format('%!i', $consumerEmi->amount + $processing_fee_amt) : '______________') . ' for your purchase from ' . $data['merchant_name'] . ' is due on ' . (isset($consumerEmi->emi_date) ? date('d M, Y', strtotime($consumerEmi->emi_date)) : '______________') . ' for your loan application no. ' . (isset($data['proFormaInvoice']->loan_application_no) ? $data['proFormaInvoice']->loan_application_no : '______________') . 'Since your Auto Debit i.e. NACH mandate has not yet been registered, please pay the EMI using ' . $rajorpay_link . ' . <br> You can reach us on +91-8928769161 or payments@creditfair.in if you have any questions.<br/>Best Regards,<br/>Team Credit Fair';
                        $view['templateDetails'] = ['templateid' => '1307166607387835447', 'entityid' => Templates::$entityid];
                        $view['templateId'] = Templates::$non_nach;
                        $view['args'] = [$data['name'], (isset($consumerEmi->amount) ? money_format('%!i', $consumerEmi->amount + $processing_fee_amt) : '______________'), $data['merchant_name'], (isset($consumerEmi->emi_date) ? date('d M, Y', strtotime($consumerEmi->emi_date)) : '______________'), (isset($data['proFormaInvoice']->loan_application_no) ? $data['proFormaInvoice']->loan_application_no : '______________'), $rajorpay_link, "+91-8928769161", "payments@creditfair.in"];

                    }

                    $view['sms'] = str_replace('<br/>', "\n", $message);
                    $view['sms'] = str_replace('<br>', "\n", $view['sms']);
                    break;
                case 6:
                    $view['body'] = view('emails.reminders.payment_confirmation', ['data' => $data, 'payment' => $consumerEmi])->render();
                    $view['subject'] = 'Payment Received - Rs ' . $consumerEmi['amount'];
                    $view['email'] = $data['email'];
                    $view['mobile_number'] = $data['mobile_number'];
                    $message = 'Dear ' . $data['name'] . ',<br/>Thanks for your payment of Rs ' . $consumerEmi['amount'] . ' for your loan ID ' . (isset($data['proFormaInvoice']->loan_application_no) ? $data['proFormaInvoice']->loan_application_no : '______________') . ' on ' . $consumerEmi['payment_date'] . ' with transaction ID (' . $consumerEmi['cf_transaction_id'] . '). <br/> Every repayment can help you improve your credit history leading to lower interest costs or access to larger loans. Let us know if you have any questions.<br/>Regards,<br/>Team Credit Fair<br/>+91-8928769161';
                    $view['sms'] = str_replace('<br/>', "\n", $message);
                    $view['sms'] = str_replace('<br>', "\n", $view['sms']);
                    $view['templateDetails'] = ['templateid' => '1307166608497572408', 'entityid' => Templates::$entityid];
                    $view['args'] = [$data['name'], $consumerEmi['amount'], (isset($data['proFormaInvoice']->loan_application_no) ? $data['proFormaInvoice']->loan_application_no : '______________'), $consumerEmi['payment_date'], $consumerEmi['cf_transaction_id'], "+91-8928769161"];
                    break;
                case 7:
                    $view['body'] = view('emails.reminders.nach_reminder_email', ['data' => $data])->render();
                    $view['subject'] = 'Urgent: Your auto-debit (NACH/ECS) mandate with Credit Fair hasn’t been setup yet';
                    $view['mobile_number'] = $data['mobile_number'];
                    $e_mandate_link = '';
                    if (!empty($data['is_emandate'])) {
                        try {
                            $e_mandate_link = Shortio::getUrl($data['is_emandate']);
                        }catch (\Exception $e){
                            $e_mandate_link = $data['is_emandate'];
                        }
                    }
                    $message = 'Dear ' . $data['name'] . '. The auto-debit (NACH/ECS) mandate for your loan ' . (isset($data['proFormaInvoice']->loan_application_no) ? $data['proFormaInvoice']->loan_application_no : '______________') . ' to make a purchase from ' . $data['merchant_name'] . ' hasn’t been registered yet. ' . (!empty($e_mandate_link) ? 'To ensure your EMIs are paid on time please click on ' . $e_mandate_link . '.' : '') . ' Please call us on +91-9967235047 if you have any questions. <br/>Best Regards,<br/>Team Credit Fair';
                    $view['sms'] = str_replace('<br/>', "\n", $message);
                    $view['sms'] = str_replace('<br>', "\n", $view['sms']);
                    break;
                case 8:
                    $view['body'] = view('emails.reminders.payment_confirmation_processing_fee', ['data' => $data, 'payment' => $consumerEmi, 'placeholder_text' => 'Processing Fees payment'])->render();
                    $view['subject'] = 'Processing Fees Received - Rs ' . $consumerEmi['amount'];
                    $view['email'] = $data['email'];
                    $view['mobile_number'] = $data['mobile_number'];
                    $view['templateDetails'] = ['templateid' => '1307167117320785973', 'entityid' => Templates::$entityid];
                    $message = 'Dear ' . $data['name'] . ',<br/>Thanks for your Processing Fees payment of Rs ' . $consumerEmi['amount'] . ' for your loan ID ' . (isset($data['proFormaInvoice']->loan_application_no) ? $data['proFormaInvoice']->loan_application_no : '______________') . ' on ' . $consumerEmi['payment_date'] . ' with transaction ID (' . $consumerEmi['cf_transaction_id'] . '). <br/> Regards,<br/>Team Credit Fair<br/>+91-8928769161';
                    $view['sms'] = str_replace('<br/>', "\n", $message);
                    $view['sms'] = str_replace('<br>', "\n", $view['sms']);
                    break;
                case 9:
                    $view['body'] = view('emails.reminders.payment_confirmation_insurance_fee', ['data' => $data, 'payment' => $consumerEmi])->render();
                    $view['subject'] = 'Insurance Premium Received - Rs ' . $consumerEmi['amount'];
                    $view['email'] = $data['email'];
                    $view['mobile_number'] = $data['mobile_number'];
                    $view['templateDetails'] = ['templateid' => '1307167117322822366', 'entityid' => Templates::$entityid];
                    $message = 'Dear ' . $data['name'] . ',<br/>Thanks for your Insurance Premium payment of Rs ' . $consumerEmi['amount'] . ' for your loan ID ' . (isset($data['proFormaInvoice']->loan_application_no) ? $data['proFormaInvoice']->loan_application_no : '______________') . ' on ' . $consumerEmi['payment_date'] . ' with transaction ID (' . $consumerEmi['cf_transaction_id'] . '). <br/> Regards,<br/>Team Credit Fair<br/>+91-8928769161';
                    $view['sms'] = str_replace('<br/>', "\n", $message);
                    $view['sms'] = str_replace('<br>', "\n", $view['sms']);
                    break;
                case 10:
                    $view['body'] = view('emails.reminders.payment_confirmation_advance_amount', ['data' => $data, 'payment' => $consumerEmi])->render();
                    $view['subject'] = 'Advance Amount Received - Rs ' . $consumerEmi['amount'];
                    $view['email'] = $data['email'];
                    $view['mobile_number'] = $data['mobile_number'];
                    $view['templateDetails'] = ['templateid' => '1307167117324243431', 'entityid' => Templates::$entityid];
                    $message = 'Dear ' . $data['name'] . ',<br/>Thanks for your Advance Amount payment of Rs ' . $consumerEmi['amount'] . ' for your loan ID ' . (isset($data['proFormaInvoice']->loan_application_no) ? $data['proFormaInvoice']->loan_application_no : '______________') . ' on ' . $consumerEmi['payment_date'] . ' with transaction ID (' . $consumerEmi['cf_transaction_id'] . '). <br/> Regards,<br/>Team Credit Fair<br/>+91-8928769161';
                    $view['sms'] = str_replace('<br/>', "\n", $message);
                    $view['sms'] = str_replace('<br>', "\n", $view['sms']);
                    break;
                case 11:
                    $view['body'] = view('emails.reminders.payment_confirmation_processing_fee', ['data' => $data, 'payment' => $consumerEmi, 'placeholder_text' => 'towards outstanding obligations'])->render();
                    $view['subject'] = 'Payment Received - Rs ' . $consumerEmi['amount'];
                    $view['email'] = $data['email'];
                    $view['mobile_number'] = $data['mobile_number'];
                    $view['templateDetails'] = ['templateid' => '1307173691770335730', 'entityid' => Templates::$entityid];
                    $view['sms'] = 'Dear '.$data['name'].', Thanks for your payment towards outstanding obligations of Rs. '.$consumerEmi['amount'].' for your loan ID '.(isset($data['proFormaInvoice']->loan_application_no) ? $data['proFormaInvoice']->loan_application_no : '______________').' on '.$consumerEmi['payment_date'].' with transaction ID ('.$consumerEmi['cf_transaction_id'].'). Regards, Credit Fair - +91-8928769161';
                    break;
            }
        }

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

    public function sendPreEMICommunication($data, $consumerEmi, $processing_fee_amt, $application_id, $emiPayments, $combined_emi) {
        if ($data['mandate'] == 1) {
            if ($combined_emi) {
                $view['body'] = view('emails.reminders.emi_due_reminder', ['data' => $data, 'consumerEmi' => $consumerEmi, 'processing_fee_amt' => $processing_fee_amt, 'pre_emi_amount' => $emiPayments[0]->pre_emi_amount, 'combined_emi' => true])->render();
                $view['subject'] = 'Pre EMI of Rs ' . money_format('%!i', $emiPayments[0]->pre_emi_amount) . 'EMI of Rs ' . (isset($consumerEmi->amount) ? money_format('%!i', $consumerEmi->amount + $processing_fee_amt) : '___________') . ' due on ' . (isset($consumerEmi->emi_date) ? date('d M, Y', strtotime($consumerEmi->emi_date)) : '___________');
                $message = 'Dear ' . $data['name'] . ',<br/>Pre EMI of Rs ' . money_format('%!i', $emiPayments[0]->pre_emi_amount) . ' and EMI of Rs ' . (isset($consumerEmi->amount) ? money_format('%!i', $consumerEmi->amount + $processing_fee_amt) : '______________') . ' will be debited on ' . (isset($consumerEmi->emi_date) ? date('d M, Y', strtotime($consumerEmi->emi_date)) : '______________') . ' for your loan application no. ' . ($data['proFormaInvoice']->loan_application_no ?? '______________') . '. Please ensure balance in your ' . $data['bank']->bank_name . ' account number ending with ' . str_repeat('X', strlen(substr($data['bank']->account_number, 0, -4))) . substr($data['bank']->account_number, -4) . ' at least one day before.<br/>Please note that it would take 3 working days to update payment in our system post debit from your account. <br/>Best Regards,<br/>Team Credit Fair';
                $view['templateDetails'] = ['templateid' => '1307173763810280525', 'entityid' => Templates::$entityid];
            } else {
                $view['body'] = view('emails.reminders.emi_due_reminder', ['data' => $data, 'consumerEmi' => $consumerEmi, 'processing_fee_amt' => $processing_fee_amt, 'pre_emi_amount' => $emiPayments[0]->pre_emi_amount, 'combined_emi' => false])->render();
                $view['subject'] = 'Pre EMI of Rs ' . money_format('%!i', $emiPayments[0]->pre_emi_amount) . ' due on ' . (isset($consumerEmi->emi_date) ? date('d M, Y', strtotime($consumerEmi->emi_date)) : '___________');
                $message = 'Dear ' . $data['name'] . ',<br/>Pre EMI of Rs ' . money_format('%!i', $emiPayments[0]->pre_emi_amount) . ' will be debited on ' . (isset($consumerEmi->emi_date) ? date('d M, Y', strtotime($consumerEmi->emi_date)) : '______________') . ' for your loan application no. ' . ($data['proFormaInvoice']->loan_application_no ?? '______________') . '. Please ensure balance in your ' . $data['bank']->bank_name . ' account number ending with ' . str_repeat('X', strlen(substr($data['bank']->account_number, 0, -4))) . substr($data['bank']->account_number, -4) . ' at least one day before.<br/>Please note that it would take 3 working days to update payment in our system post debit from your account. <br/>Best Regards,<br/>Team Credit Fair';
                $view['templateDetails'] = ['templateid' => '1307173201364042442', 'entityid' => Templates::$entityid];
            }
        } else {
            $razorpaydata['email'] = "";
            $razorpaydata['lender_id'] = $data['lender_id'];
            $razorpaydata['id'] = $application_id;
            if ($combined_emi) {
                $razorpaydata['amount'] = $consumerEmi->amount + $processing_fee_amt + $emiPayments[0]->pre_emi_amount;
                $razorpaydata['purpose'] = 'emi';
                if ($processing_fee_amt > 0) {
                    $razorpaydata['purpose'] = 'emi_and_processing_fee';
                }
            } else {
                $razorpaydata['amount'] = $emiPayments[0]->pre_emi_amount;
                $razorpaydata['purpose'] = 'Pre-EMI';
            }

            $razorpaydata['emi_date'] = $consumerEmi->emi_date;
            $rajorpay_link = $this->getrazorpaylink($razorpaydata);

            if ($combined_emi) {
                $view['body'] = view('emails.reminders.emi_due_reminder_with_payment_link', ['data' => $data, 'consumerEmi' => $consumerEmi, 'rajorpay_link' => $rajorpay_link, 'processing_fee_amt' => $processing_fee_amt, 'pre_emi_amount' => $emiPayments[0]->pre_emi_amount, 'combined_emi' => true])->render();
                $view['subject'] = 'Pre EMI of Rs ' . money_format('%!i', $emiPayments[0]->pre_emi_amount) . 'EMI of Rs ' . (isset($consumerEmi->amount) ? money_format('%!i', $consumerEmi->amount + $processing_fee_amt) : '___________') . ' due on ' . (isset($consumerEmi->emi_date) ? date('d M, Y', strtotime($consumerEmi->emi_date)) : '___________');
                $message = 'Dear ' . $data['name'] . ',<br/>Pre EMI of Rs ' . money_format('%!i', $emiPayments[0]->pre_emi_amount) . ' and EMI of Rs ' . (isset($consumerEmi->amount) ? money_format('%!i', $consumerEmi->amount + $processing_fee_amt) : '______________') . ' for your purchase from ' . $data['merchant_name'] . ' is due on ' . (isset($consumerEmi->emi_date) ? date('d M, Y', strtotime($consumerEmi->emi_date)) : '______________') . ' for your loan application no. ' . ($data['proFormaInvoice']->loan_application_no ?? '______________') . 'Since your Auto Debit i.e. NACH mandate has not yet been registered, please pay the EMI using ' . $rajorpay_link . ' . <br> You can reach us on +91-8928769161 or payments@creditfair.in if you have any questions.<br/>Best Regards,<br/>Team Credit Fair';
                $view['templateDetails'] = ['templateid' => '1307173771172350723', 'entityid' => Templates::$entityid];
            } else {
                $view['body'] = view('emails.reminders.emi_due_reminder_with_payment_link', ['data' => $data, 'consumerEmi' => $consumerEmi, 'rajorpay_link' => $rajorpay_link, 'processing_fee_amt' => $processing_fee_amt, 'pre_emi_amount' => $emiPayments[0]->pre_emi_amount, 'combined_emi' => false])->render();
                $view['subject'] = 'Pre EMI of Rs ' . money_format('%!i', $emiPayments[0]->pre_emi_amount) . ' due on ' . (isset($consumerEmi->emi_date) ? date('d M, Y', strtotime($consumerEmi->emi_date)) : '___________');
                //TODO: template ID
                $message = 'Dear ' . $data['name'] . ',<br/>Pre EMI of Rs ' . money_format('%!i', $emiPayments[0]->pre_emi_amount) . ' for your purchase from ' . $data['merchant_name'] . ' is due on ' . (isset($consumerEmi->emi_date) ? date('d M, Y', strtotime($consumerEmi->emi_date)) : '______________') . ' for your loan application no. ' . ($data['proFormaInvoice']->loan_application_no ?? '______________') . 'Since your Auto Debit i.e. NACH mandate has not yet been registered, please pay the EMI using ' . $rajorpay_link . ' . <br> You can reach us on +91-8928769161 or payments@creditfair.in if you have any questions.<br/>Best Regards,<br/>Team Credit Fair';
                $view['templateDetails'] = ['templateid' => '1307166607387835447', 'entityid' => Templates::$entityid];
            }
        }

        $view['sms'] = str_replace('<br/>', "\n", $message);
        $view['sms'] = str_replace('<br>', "\n", $view['sms']);

        $application = ConsumerApplication::with('merchant')->where('id', $application_id)->first(['email', 'mobile_number', 'state']);

        if (isset($application->email) && !empty($application->email) && UserEmails::isValid($application->email)) {
            \Mail::send('emails.blank',
                ['body' => $view['body']],
                function ($message) use ($application, $view) {
                    $message->to($application->email)->subject($view['subject']);
                }
            );
        }
        if (isset($application->mobile_number) && !empty($application->mobile_number) && isset($view['sms'])) {
            $mobile = '91' . $application->mobile_number;
            send_sms($mobile, ['message' => $view['sms'], 'id' => $application_id, 'id_type' => 'application_id', 'message_type' => "payment", 'templateId' => $view['templateId'] ?? '', 'args' => $view['args'] ?? '', 'templateDetails' => $view['templateDetails'] ?? '']);
        }
    }

    public function setReminders($communication_id)
    {
        $status = false;
        $message = '';
        try {
            if ($communication_id > 0) {
                $consumer_application_id = Input::get('consumer_application_id');
                $application = ConsumerApplication::with('merchant', 'application_element')->where('id', $consumer_application_id)->first(['id', 'name', 'email', 'mobile_number', 'lender_id', 'loan_amount', 'merchant_id']);
                switch ($communication_id) {
                    case Input::get('text') == 'rejected':
                        if (isset($application->email) && $application->email) {
                            $status = $this->applicationRejectMail($application);
                        }

                        $this->sendMessageToMerchant(Input::get('text'), $consumer_application_id);

                        ConsumerApplication::where('id', $consumer_application_id)
                            ->update(['state' => $this->status['rejected']]);
                        $this->webhook($consumer_application_id, ['merchant_id' => $application->merchant_id, 'type' => 'Application-Webhook', 'status' => Input::get('text'), 'data' => $this->getMConnectPayload($consumer_application_id, Input::get('text'), ['reason' => Input::has('rejection_reason') ? Input::get('rejection_reason') : ''])]);

                        StatusLogs::insert([
                            'application_id' => $consumer_application_id,
                            'user_id' => Input::has('user_id') ? Input::get('user_id') : (Auth::user() ? Auth::user()->id : 107),
                            'status' => $this->status['rejected'],
                            'reason' => Input::has('rejection_reason') ? Input::get('rejection_reason') : '',
                            'created_at' => Carbon::now()->toDateTimeString()
                        ]);

                        if (Input::has('rejection_reason') && Input::get('rejection_reason')) {
                            $comment = 'Rejection Reason: ' . Input::get('rejection_reason');
                            saveComment($comment, $consumer_application_id, Auth::user()->id);
                        }

                        if (isset($application->application_element) && (!$application->application_element->co_applicant_for_signing == 1 && !$application->application_element->co_applicant_for_income == 1)) {
                            if (Input::get('sms') != '') {
                                //SMS notification
                                $message = str_replace('<br>', "\n", Input::get('sms'));
                                $mobile_number = '91' . $application->mobile_number;
                                $templateId = Templates::$rejected_customer;
                                $args = [$application->name, $application->loan_amount];
                                send_sms($mobile_number, ['message' => $message, 'id' => $consumer_application_id, 'id_type' => 'application_id', 'templateId' => $templateId, 'args' => $args]);
                            }
                        }

                        $status = true;
                        break;
                    case 1:
                        if (isset($application->email)) {
                            $status = $this->documentSubmission($application);
                        } else {
                            $message = 'Email address is missing in application';
                        }
                        break;
                    case 2:
                        if (isset($application->email)) {
                            $status = $this->preApproval($application);
                        } else {
                            $message = 'Email address is missing in application';
                        }
                        break;
                    case 3:
                        if (isset($application->email)) {
                            $status = $this->informMerchantOfPreApproval();
                        } else {
                            $message = 'Email address is missing in application';
                        }
                        break;
                    case 4:
                        if (isset($application->email)) {
                            $status = $this->afterDocumentSubmission($application);
                        } else {
                            $message = 'Email address is missing in application';
                        }
                        break;
                    case 5:
                        $status = $this->emiDueReminder($application);
                        break;
                    case 7:
                        $status = $this->reminderNach($application);
                        break;

                }
            }
        } catch (\Exception $e) {
            $message = "Exception occurred while setting reminder emails.".$e->getMessage().$e->getFile().$e->getLine().$e->getTraceAsString();
        }

        return response()->json(['status' => ($status) ? 'OK' : 'FAIL', 'message' => $message, 'type' => Input::get('text')], 200);
    }

    public function documentSubmission($application)
    {
        $body = Input::has('body') ? Input::get('body') : false;
        if ($body) {
            $subject = Input::get('subject');
            $cc_emails = Input::get('cc_emails') != '' ? explode(',', trim(Input::get('cc_emails'))) : [];
            \Mail::send('emails.blank',
                ['body' => $body]
                , function ($message) use ($subject, $cc_emails, $application) {
                    $message->to($application->email)->subject(($subject) ? $subject : 'Gentle reminder for Loan Documents');
                    $message->cc(_env('NOTIFY_EMAIL', ''));
                    if (count($cc_emails) > 0) {
                        array_push($cc_emails, _env('NOTIFY_EMAIL', ''));
                        $message->cc($cc_emails);
                    }
                });

            return true;
        }

        return $body;

    }

    public function reminderNach($application)
    {
        $body = Input::has('body') ? Input::get('body') : false;
        if ($body) {
            if ($application->email) {
                $subject = Input::get('subject');
                $cc_emails = Input::get('cc_emails') != '' ? explode(',', trim(Input::get('cc_emails'))) : [];
                \Mail::send('emails.blank', [
                    'body' => $body
                ], function ($message) use ($subject, $cc_emails, $application) {
                    $message->to($application->email)->subject(($subject) ? $subject : '');
                    if (count($cc_emails) > 0) {
                        array_push($cc_emails, _env('NOTIFY_EMAIL', ''));
                        $message->cc($cc_emails);
                    } else {
                        $message->cc(_env('NOTIFY_EMAIL', ''));
                    }
                    if ($application->lender_id == 2) {
                        $message->attach(storage_path() . '/csv/KM_Updated_NACH.pdf', ['as' => 'Nach']);
                        $message->attach(storage_path() . '/csv/km_sample_nach.pdf', ['as' => 'Sample Nach']);
                    } else {
                        $message->attach(storage_path() . '/csv/Pride NACH Form.pdf', ['as' => 'Nach']);
                        $message->attach(storage_path() . '/csv/pride_nach_sample.pdf', ['as' => 'Sample Nach']);
                    }
                });
            }

            if (Input::get('sms') != '') {
                //SMS notification
                $message = str_replace('<br>', "\n", Input::get('sms'));
                $mobile_number = '91' . $application->mobile_number;
                send_sms($mobile_number, ['message' => $message, 'id' => $application->id, 'id_type' => 'application_id']);
            }

            return true;
        }

        return $body;
    }

    public function emiDueReminder($application)
    {
        $body = Input::has('body') ? Input::get('body') : false;
        if ($body) {
            $subject = Input::get('subject');
            $cc_emails = Input::get('cc_emails') != '' ? explode(',', trim(Input::get('cc_emails'))) : [];
            \Mail::send('emails.blank', [
                'body' => $body
            ], function ($message) use ($subject, $cc_emails, $application) {
                $message->to($application->email)->subject(($subject) ? $subject : 'Requesting repayment on your loan');
                $message->cc(_env('NOTIFY_EMAIL', ''));
                if (count($cc_emails) > 0) {
                    array_push($cc_emails, _env('NOTIFY_EMAIL', ''));
                    $message->cc($cc_emails);
                }
            });

            if (Input::get('sms') != '') {
                //SMS notification
                $message = str_replace('<br>', "\n", Input::get('sms'));
                $mobile_number = '91' . $application->mobile_number;
                send_sms($mobile_number, ['message' => $message, 'id' => $application->id, 'id_type' => 'application_id']);
            }

            return true;
        }

        return $body;
    }

    public function afterDocumentSubmission($application)
    {
        $body = Input::has('body') ? Input::get('body') : false;
        if ($body) {
            $subject = Input::get('subject');
            $cc_emails = Input::get('cc_emails') != '' ? explode(',', trim(Input::get('cc_emails'))) : [];
            \Mail::send('emails.blank', [
                'body' => $body
            ], function ($message) use ($subject, $cc_emails, $application) {
                $message->to($application->email)->subject(($subject) ? $subject : 'We have received your documents');
                $message->cc(_env('NOTIFY_EMAIL', ''));
                if (count($cc_emails) > 0) {
                    array_push($cc_emails, _env('NOTIFY_EMAIL', ''));
                    $message->cc($cc_emails);
                }
            });

            return true;
        }

        return $body;
    }

    public function informMerchantOfPreApproval()
    {

    }

    public function applicationRejectMail($application, $autoReject = false)
    {
        $body = Input::has('body') ? Input::get('body') : false;
        $subject = Input::get('subject');

        if ((isset($application->application_element) && ($application->application_element->co_applicant_for_signing == 1 || $application->application_element->co_applicant_for_income == 1)) || $autoReject) {
            $body = 'Dear ' . $application->name . ',<br/>

We cannot approve your application of Rs ' . $application->loan_amount . ' for purchase from ' . $application->merchant->merchant_name . ' at this time. Please add a co-applicant with:

<ul>
<li>PAN Card</li>
<li>Address proof (Aadhar Card or Utility Bill)</li>
<li>Income proof - 3 months Salary Slip OR 2 year Income Tax Returns</li>
<li>Bank Statement - last 6 months</li>
</ul><br/>

If a co-applicant isn’t available, we’d be happy to reconsider you after 3 months.<br/>

If you have any questions about our decision, please contact us at ops@creditfair.in.<br/><br/>

Regards,<br/>

Team Credit Fair<br/>

ops@creditfair.in<br/>

+91-9967235047';

            $subject = "We can't approve your application of Rs $application->loan_amount, please add co-applicant";

            $sms = 'Dear ' . $application->name . ', We cannot approve your application of Rs ' . $application->loan_amount . ' based on current documents. Please add a co-applicant with <br/>1) PAN<br/>2) Aadhar Card or Utility Bill<br/>3) Salary Slip (3 months) OR ITR (2 years)<br/>4) Bank Statement (6 months)<br/>If a co-applicant is not available, we would be happy to reconsider you after 3 months. <br/>Regards,<br/>Team Credit Fair<br/>ops@creditfair.in';


            if($templateData = $this->getPreferredLanguageTemplate($application, [], 'rejected', 'customer')){
                $sms = $templateData['sms'];
                $templateId = $templateData['templateId'];
                $args = $templateData['args'];

                send_sms($application->mobile_number, ['message' => $sms, 'id' => $application->id, 'id_type' => 'application_id', 'templateId' => $templateId, 'args' => $args]);
            }else{
                send_sms($application->mobile_number, ['message' => $sms, 'id' => $application->id, 'id_type' => 'application_id']);
            }

        }


        if ($body) {
            $cc_emails = Input::get('cc_emails') != '' ? explode(',', trim(Input::get('cc_emails'))) : [];
            if ($cc_emails || $application->email) {
                \Mail::send('emails.blank', [
                    'body' => $body
                ], function ($message) use ($subject, $cc_emails, $application) {
                    $message->to($application->email)->subject(($subject) ? $subject : 'Thanks for your loan application');
                    //$message->cc(_env('NOTIFY_EMAIL', ''));
                    if (count($cc_emails) > 0) {
                        if($subject != 'Thanks for your loan application') {
                            array_push($cc_emails, _env('NOTIFY_EMAIL', ''));
                        }
                        $message->cc($cc_emails);
                    }
                });
            }

            return true;
        }

        return $body;
    }

    public function preApproval($application)
    {

        $body = Input::has('body') ? Input::get('body') : false;

        if ($body) {
            $subject = Input::get('subject');
            $cc_emails = Input::get('cc_emails') != '' ? explode(',', trim(Input::get('cc_emails'))) : [];
            \Mail::send('emails.blank', [
                'body' => $body
            ], function ($message) use ($subject, $cc_emails, $application) {
                $message->to($application->email)->subject(($subject) ? $subject : 'You have been pre-approved by Credit Fair!');
                $message->cc(_env('NOTIFY_EMAIL', ''));
                if (count($cc_emails) > 0) {
                    $message->cc($cc_emails);
                }
            });

            return true;
        }

        return $body;
    }

    public function getTransactionBank($id)
    {
        $application = ConsumerApplicationElement::where('application_id', $id)->first(['bank_id']);

        if (!$application->bank_id) {
            $application = ConsumerApplication::where('id', $id)->first(['lender_id']);
            if ($application->lender_id) {
                $bank = LenderBank::where('lender_id', $application->lender_id)->orderBy('created_at', 'asc')->first(['id']);
                return isset($bank->id) ? $bank->id : '';
            }
        }

        return isset($application->bank_id) ? $application->bank_id : '';
    }

    public function getProFormaInvoice($id)
    {
        $data = [];
        $proFormaInvoice = ProFormaInvoice::where('application_id', $id)->first();
        $consumerdetails = ConsumerApplication::with('merchant','activeOffer','application_element.merchant_center')->where('id', $id)->first();
        if ($consumerdetails->merchant) {
            $loan_application_no = $this->getLoanApplicationID($id, $consumerdetails->merchant);
        }
        $data['processing_fee_first_emi'] = isset($consumerdetails->activeOffer) && isset($consumerdetails->activeOffer->processing_fee_first_emi) ? $consumerdetails->activeOffer->processing_fee_first_emi : 0;
        if (isset($proFormaInvoice->id) && isset($proFormaInvoice->loan_application_no)) {
            if ($proFormaInvoice->loan_application_no == "") {
                $proFormaInvoice->loan_application_no = isset($loan_application_no) ? $loan_application_no : null;
            }
            if($consumerdetails && $consumerdetails->merchant && $consumerdetails->merchant->collect_advance_amount){
                $proFormaInvoice->merchant_collected_advance_amount = 1;
            }else{
                $proFormaInvoice->merchant_collected_advance_amount = 0;
            }
            $data['loan_application_no'] = isset($loan_application_no) ? $loan_application_no : null;
            $proFormaInvoice->save();
        } else if(!isset($proFormaInvoice->id)) {
            if ($consumerdetails->merchant) {
                $data['loan_application_no'] = isset($loan_application_no) ? $loan_application_no : null;
                $proFormInvoice = new ProFormaInvoice();
                $proFormInvoice->processing_fee_by_merchant = $consumerdetails->merchant->is_collected;
                $proFormInvoice->application_id = $id;
                $merchantInsuranceConfig = (new AccountingController())->getMerchantInsuranceConfig($id);
                $proFormInvoice->insurance_premium_by_merchant = $merchantInsuranceConfig['insurance_premium_by_merchant'];
                $proFormInvoice->insurance_premium_applicable = $merchantInsuranceConfig['insurance_premium_applicable'];
                $proFormInvoice->insurance_coverage = $merchantInsuranceConfig['insurance_coverage'];
                $proFormInvoice->processing_fee_by_merchant = $merchantInsuranceConfig['processing_fee_by_merchant'];
                $proFormInvoice->loan_application_no = isset($loan_application_no) ? $loan_application_no : null;
                if($consumerdetails && $consumerdetails->merchant && $consumerdetails->merchant->collect_advance_amount){
                    $proFormInvoice->merchant_collected_advance_amount = 1;
                }else{
                    $proFormInvoice->merchant_collected_advance_amount = 0;
                }
                $proFormInvoice->save();
            }
        }else if (isset($proFormaInvoice->id)){
            $data['loan_application_no'] = $proFormaInvoice->loan_application_no;
        }

        if (isset($proFormaInvoice->id)){

            $gst_number = isset($consumerdetails->application_element->merchant_center->gst_number) ? $consumerdetails->application_element->merchant_center->gst_number : '';
            if(!$gst_number){
                $gst_number = $consumerdetails->merchant ? $consumerdetails->merchant->gst_number : '';
            }
            $center = isset($consumerdetails->application_element->merchant_center->name) ? $consumerdetails->application_element->merchant_center->name : '';

            $data['gst_number'] = $gst_number ? $gst_number : ($proFormaInvoice->gst_number ? $proFormaInvoice->gst_number : '');
            $data['center_name'] = $center ? $center : ($proFormaInvoice->center_name ? $proFormaInvoice->center_name : '');
            $data['customer_name'] = $consumerdetails->name ? $consumerdetails->name : ($proFormaInvoice->customer_name ? $proFormaInvoice->customer_name : '');
            $data['treatment_name'] = $proFormaInvoice->treatment_name ? $proFormaInvoice->treatment_name : '';
            $data['customer_registration_date'] = $proFormaInvoice->customer_registration_date ? $proFormaInvoice->customer_registration_date : '';
            $data['customer_registration_number'] = $proFormaInvoice->customer_registration_number ? $proFormaInvoice->customer_registration_number : '';
            $data['processing_fee_by_merchant'] = $proFormaInvoice->processing_fee_by_merchant ? $proFormaInvoice->processing_fee_by_merchant : $consumerdetails->merchant->is_collected;
        }
        return response()->json($data, 200);
    }

    public function getLoanApplicationID($id, $merchant)
    {
        $type = 7;

        if($merchant->id == 5026){
            $type = 8;
        }

        if (strlen($id) < $type) {
            $diff = $type - strlen($id);
            $concatstring = "";
            for ($i = 0; $i < $diff; $i++) {
                $concatstring = $concatstring . "0";
            }
        }
        return $merchant['slug'] . $concatstring . $id;
    }

    public function saveInsuranceSummary(){
        $id = Input::get('id');
        $invoice = ProFormaInvoice::where('application_id', $id)->first(['id']);
        $sendCommunication = 0;
        $application = ConsumerApplication::with('merchant', 'activeOffer', 'emi')->where('id', $id)->first(['id','merchant_id','approved_amount','offer_id']);
        if (isset($invoice->id)) {
            $invoice->insurance_premium_applicable = Input::get('insurance_premium_applicable');
            $invoice->insurance_premium_amount = Input::get('insurance_premium_applicable') == 1 ? Input::get('insurance_premium_amount') : 0;
            $invoice->insurance_premium_by_merchant = Input::get('insurance_premium_by_merchant');
            $invoice->liability_hold = (int)Input::get('liability_hold');
            $invoice->fldg_applied = (int)Input::get('fldg_applied');
            $invoice->fldg_applied_category = (int)Input::get('fldg_category');
            $invoice->insurance_coverage = (int)Input::get('insurance_coverage');
            if(Input::has('processing_fee_impact') && Input::get('processing_fee_impact') && $invoice->processing_fee_by_merchant != Input::get('processing_fee')){
                $invoice->processing_fee_by_merchant = Input::get('processing_fee');
                if(Input::has('send_processing_fee_communication') && Input::get('send_processing_fee_communication')){
                    $sendCommunication = 1;
                }
            }

            if($application && $application->merchant && ($application->merchant->collect_advance_amount || Input::has('advance_amount_collect'))){
                $invoice->merchant_collected_advance_amount = Input::get('advance_amount_collect') ? 1 : 0;
            }
            if (!isset($invoice->loan_application_no)) {
                $loan_application_no = $this->getLoanApplicationID($id, $application->merchant);
                $invoice->loan_application_no = isset($loan_application_no) ? $loan_application_no : null;
            }
            $invoice->update();
        } else {
            $proFormInvoice = new ProFormaInvoice();
            $proFormInvoice->insurance_premium_applicable = Input::get('insurance_premium_applicable');
            $proFormInvoice->insurance_premium_amount = Input::get('insurance_premium_applicable') == 1 ? Input::get('insurance_premium_amount') : 0;
            $proFormInvoice->insurance_premium_by_merchant = Input::get('insurance_premium_collected_by_merchant');
            $proFormInvoice->liability_hold = (int)Input::get('liability_hold');
            $proFormInvoice->fldg_applied = (int)Input::get('fldg_applied');
            $proFormInvoice->fldg_applied_category = (int)Input::get('fldg_category');
            $proFormInvoice->insurance_coverage = (int)Input::get('insurance_coverage');

            if(Input::has('processing_fee_impact') && Input::get('processing_fee_impact') && $proFormInvoice->processing_fee_by_merchant != Input::get('processing_fee')){
                $proFormInvoice->processing_fee_by_merchant = Input::get('processing_fee');
                if(Input::has('send_processing_fee_communication') && Input::get('send_processing_fee_communication')){
                    $sendCommunication = 1;
                }
            }

            if($application && $application->merchant && ($application->merchant->collect_advance_amount || Input::get('advance_amount_collect'))){
                $proFormInvoice->merchant_collected_advance_amount = Input::get('advance_amount_collect') ? 1 : 0;
            }
            if (!isset($proFormInvoice->loan_application_no)) {
                $loan_application_no = $this->getLoanApplicationID($id, $application->merchant);
                $proFormInvoice->loan_application_no = isset($loan_application_no) ? $loan_application_no : null;
            }

            $proFormInvoice->application_id = $id;
            $proFormInvoice->save();
        }

        if (\Illuminate\Support\Facades\Session::has('PF_Surcharge_Discount|-63')) {
            $riskBasedCalculation = DB::selectOne("SELECT id, adjustment_type, adjustment_value_type, adjustment_value from risk_based_pricing_calculation where application_id = $id and deleted_at is null");
            if (Input::has('pf_details') && Input::get('pf_details')) {
                $pf_details = Input::get('pf_details');
                $pf_details['application_id'] = $id;
                $pf_details['payment_type'] = 'processing_fee';
            }
            if (isset($pf_details) && isset($riskBasedCalculation->id)) {
                DB::table('risk_based_pricing_calculation')
                    ->where('application_id', $id)
                    ->update([
                        'adjustment_type' => $pf_details['adjust_type'],
                        'adjustment_value' => $pf_details['pf_increase_value'],
                        'adjustment_value_type' => $pf_details['value_type'],
                        'total_amount' => $pf_details['pf_summary_value'],
                        'updated_at' => Carbon::now(),
                        'deleted_at' => null
                    ]);
                (new RiskController(new Request()))->saveRiskBasedPricingCalculationLog($pf_details);
            } else if (isset($pf_details) && !isset($riskBasedCalculation->id)) {
                // new entry
                $result = (new RiskController(new Request()))->saveRiskBasedPricingCalculation($pf_details);
            } else {
                // delete condition
                if (isset($riskBasedCalculation->id)) {
                    DB::table('risk_based_pricing_calculation')
                        ->where('application_id', $id)
                        ->update([
                            'deleted_at' => Carbon::now()
                        ]);
                }
            }
        }

        if(Input::has('insurance_cf_solar_discount')){
            $application_element = ConsumerApplicationElement::where('application_id', $id)->first();
            if($application_element){
                $application_element->discount_by_cf = Input::get('insurance_cf_solar_discount') ?? 0;
                $application_element->save();
            }
        }
        if($sendCommunication){
            $this->sendProcessingFeeCommunicationToCustomer($id);
        }

        $this->saveLiabilityPercent($application, $id);

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


    public function sendProcessingFeeCommunicationToCustomer($application_id){
        if(!Input::get('processing_fee')){
            $request = new Request();
            $request->request->add([
                'type' => 'Sanction Letter',
                'bot' => true
            ]);
            $document = (new ConsumerDocument($request));
            $documentDetails = $document->getDocument($application_id);
            if(isset($documentDetails['user']['processing_fee_link']) && $documentDetails['user']['processing_fee_link']){
                $message = "Dear ".$documentDetails['user']['customer_name'].",<br/>Congratulations! Your loan application has been successfully processed for amount of ".$documentDetails['user']['loan_amount']." towards your purchase at ".$documentDetails['user']['merchant_name'].". E-sign your loan agreement online here ".$documentDetails['user']['esignlink']." Pay processing fees ".$documentDetails['user']['processing_fee_link'] . " <br/> - Credit Fair";
                $entity = ['templateid' => '1307167039600184621', 'entityid' => Templates::$entityid];
                send_sms($documentDetails['user']['customer_mobile'], ['message' => $message, 'templateDetails' => $entity]);
            }

        }
    }

    public function saveProFormaInvoiceData($id)
    {
        $invoice = ProFormaInvoice::where('application_id', $id)->first(['id', 'insurance_premium_amount']);
        $application = ConsumerApplication::with('merchant')->where('id', $id)->first(['id','merchant_id']);
        if (isset($invoice->id)) {
            $insurance_premium_amount = $invoice->insurance_premium_amount;
            $invoice->fill(Input::all());
            if(!Input::has('init_type')){
                if( Input::has('insurance_premium_by_merchant') && Input::has('insurance_premium_amount')) {
                    $invoice->insurance_premium_by_merchant = (Input::get('insurance_premium_by_merchant') == 'on') ? 1 : 0;
                    $invoice->insurance_premium_amount = Input::get('insurance_premium_amount') ?? null;
                }
            }else{
                $invoice->insurance_premium_amount = $insurance_premium_amount;
            }
            $invoice->processing_fee_by_merchant = (Input::get('processing_fee_by_merchant') == 'on') ? 1 : 0;
            if (!isset($invoice->loan_application_no)) {
                $loan_application_no = $this->getLoanApplicationID($id, $application->merchant);
                $invoice->loan_application_no = isset($loan_application_no) ? $loan_application_no : null;
            }
            $invoice->update();
        } else {
            $proFormInvoice = new ProFormaInvoice();
            $proFormInvoice->fill(Input::all());
            $proFormInvoice->processing_fee_by_merchant = (Input::get('processing_fee_by_merchant') == 'on') ? 1 : 0;
            $proFormInvoice->insurance_premium_by_merchant = (Input::get('insurance_premium_by_merchant') == 'on') ? 1 : 0;
            $proFormInvoice->insurance_premium_applicable = (Input::get('insurance_premium_applicable') == 'on') ? 1 : 0;
            $proFormInvoice->insurance_premium_amount = Input::get('insurance_premium_amount') ?? null;
            $proFormInvoice->application_id = $id;
            if (!isset($proFormInvoice->loan_application_no)) {
                $loan_application_no = $this->getLoanApplicationID($id, $application->merchant);
                $proFormInvoice->loan_application_no = isset($loan_application_no) ? $loan_application_no : null;
            }
            $proFormInvoice->save();
        }
        return response()->json(['status' => 'OK'], 200);
    }

    public function isMandateActive($consumerApplication, $status = 'active')
    {
        $mandate = 0;
        if (isset($consumerApplication->mandateMany[0])) {
            foreach ($consumerApplication->mandateMany as $mandatedata) {
                if ($mandatedata->status == $status) {
                    if ($status == 'submitted' || $status == 'accepted') {
                        $umrn = 1;
                    } else {
                        $umrn = $mandatedata->umrn;
                    }
                    if (!empty($umrn)) {
                        $mandate = 1;
                    }
                }
            }
        }

        return $mandate;
    }

    public function getDetails($application_id = 0)
    {
        $consumer_application_id = (Input::has('consumer_application_id')) ? Input::get('consumer_application_id') : $application_id;
        $consumerApplication = ConsumerApplication::with('merchant', 'bank_details', 'emi', 'proFormaInvoice', 'mandateMany')->find($consumer_application_id);
        $mandate = $this->isMandateActive($consumerApplication);
        if (!$mandate){
            $mandate = $this->isMandateActive($consumerApplication, 'accepted');
        }

        if (isset($consumerApplication->name)) {
            $data = [
                'name' => $consumerApplication->name,
                'mobile_number' => $consumerApplication->mobile_number,
                'co_applicant_name' => isset($consumerApplication->co_applicant_name) ? $consumerApplication->co_applicant_name : '',
                'email' => $consumerApplication->email,
                'merchant_name' => isset($consumerApplication->merchant->merchant_name) ? $consumerApplication->merchant->merchant_name : '',
                'employee_status' => $consumerApplication->employee_status,
                'bank' => $consumerApplication->bank_details,
                'loan_amount' => $consumerApplication->approved_amount,
                'loan_amount_' => $consumerApplication->loan_amount,
                'loan_received' => $consumerApplication->created_at,
                'consumer_emi' => isset($consumerApplication->emi) ? $consumerApplication->emi : '',
                'proFormaInvoice' => isset($consumerApplication->proFormaInvoice) ? $consumerApplication->proFormaInvoice : '',
                'mandate' => $mandate,
                'lender_id' => $consumerApplication->lender_id,
                'disclaimer' => 1,
                'after_approval' => (in_array($consumerApplication->state, ['approved', 'disbursement checklist done', 'ready for disbursement', 'disbursed', 'nach registered'])) ? 1 : 0,
                'offer_expiry' => $this->getOfferExpiry($consumer_application_id),
                'is_emandate' => $this->getEMandate($application_id)
            ];

            return $data;
        }

        return false;
    }

    public function getEMandate($application_id)
    {
        $mandate = Mandate::where('consumer_application_id', $application_id)->where('mode', 'lotuspay_emandate')->whereIn('status', ['acknowledged', 'pending', 'pending_submission', 'submitted'])->first(['mandate_url']);
        if (isset($mandate->mandate_url)) {
            return $mandate->mandate_url;
        }
        return '';
    }

    public function getOfferExpiry($id)
    {
        $status = StatusLogs::where('application_id', $id)
            ->where('status', 'approved')->orderBy('created_at', 'desc')->first(['created_at']);
        if (isset($status->created_at)) {
            return date('d M, Y', strtotime($status->created_at));
        }
        return date('d M, Y');
    }

    public function getEMIOption($id)
    {
        $data = [];

        $application_element = ConsumerApplicationElement::where('application_id', $id)->first(['discount_by_cf']);
        $ProFormaInvoice = ProFormaInvoice::where('application_id', $id)->first(['insurance_coverage', 'insurance_premium_by_merchant', 'insurance_premium_amount']);
        $app = ConsumerApplication::where('id', $id)->first(['approved_amount']);
        $insurance_data = $this->calculateInsurance(new Request(['id' => $id,'loan_amount'=> $app->approved_amount, 'discount' => $application_element->discount_by_cf, 'tenure_in_years' => $ProFormaInvoice->insurance_coverage ?? 0]));
        $_insurance_data = $insurance_data->getData();
        if(isset($_insurance_data->success) && $_insurance_data->success){
            ProFormaInvoice::where('application_id', $id)->update(['insurance_premium_amount' => $_insurance_data->insurance_amount]);
        }

        $application = ConsumerApplication::with('proFormaInvoice','merchant', 'application_element', 'activeOffer', 'emi', 'lender')->where('id', $id)->first(['id','merchant_id', 'offer_id', 'approved_amount as loan_amount', 'purpose', 'state','lender_id']);

        if (in_array($application->state, ['nach registered', 'disbursed', 'closed'])) {
            \Session::flash('error', 'You can\'t change EMI after ' . $application->state);
            return \redirect()->to('/admin/consumer-applications/edit/' . $id);
        }

        if ($application->loan_amount == 0) {
            \Session::flash('error', 'Please added approved amount before generating EMIs');
            //return redirect()->to('/admin/consumer-applications/edit/' . $id);
        }

        if (isset($application->merchant_id) && !empty($application->merchant_id)) {
            $offer = MerchantOffers::where('id', $application->offer_id)->first(['interest_type_id']);
            if (isset($application->offer_id)) {
                $request = new Request();
                $request->attributes->add(['merchant_id' => $application->merchant_id, 'loan_amount' => $application->loan_amount, 'merchant_offer_id' => $application->offer_id, 'category_id' => $application->purpose, 'interest_type_id' => $offer->interest_type_id, 'application_id' => $id]);
                $calculation = new \App\Http\Controllers\Admin\EMICalculation($request);
                try {
                    $data['calculation'] = $calculation->prepareCalculation();
                } catch (\Exception $e) {
                    \Session::flash('error', 'Merchant offer not added correctly. Please check subvention type');
                    return redirect()->back();
                }
            }

            $riskBasedCalculationDetails = DB::selectOne("SELECT * from risk_based_pricing_calculation where application_id = $id and deleted_at is null");
            $disbursement_offers_data = DisbursementOffers::where('application_id', $id)->where('offer_id', $application->offer_id)->whereNull('deleted_at')->orderby('phase', 'asc')->get()->keyby('phase');
            $total_phases = $disbursement_offers_data->count();
            $data['first_emi_date'] = isset($application->emi->emi_date) && !empty($application->emi->emi_date) ? date('d/m/Y', strtotime($application->emi->emi_date)) : '';
            $data['offer_id'] = $application->offer_id;
            $data['loan_amount'] = $application->loan_amount;
            $data['category_id'] = $application->purpose;
            $data['product_id'] = isset($application->application_element->product_name) && is_array($application->application_element->product_name) ? explode(',',$application->application_element->product_name) : ((isset($application->application_element->product_name)) ? $application->application_element->product_name : '');
            $data['pf_surcharge'] = isset($application->emi->pf_surcharge_percent) ? $application->emi->pf_surcharge_percent : 0;
            $data['enable_pf_adjustment'] = isset($riskBasedCalculationDetails->id) ? true : false;
            $data['risk_based_pricing_adjustment'] = isset($riskBasedCalculationDetails->adjustment_type) ? $riskBasedCalculationDetails->adjustment_type : 'increase';
            $data['risk_based_pricing_value'] = isset($riskBasedCalculationDetails->adjustment_value) ? $riskBasedCalculationDetails->adjustment_value : '';
            $data['risk_based_pricing_value_type'] = isset($riskBasedCalculationDetails->adjustment_value_type) ? $riskBasedCalculationDetails->adjustment_value_type : null;
            $offer_linked_pf = (new RiskController(new Request()))->getOfferLinkedPF($application);
            $data['offerLinkedPF'] = round($offer_linked_pf);
            $data['total_pf'] = round($offer_linked_pf) + $application->emi->pf_surcharge_amount + $application->emi->pf_surcharge_gst;
            $data['merchant_id'] = $application->merchant_id;
            $data['proFormaInvoice'] = $application->proFormaInvoice;
            $data['merchant_data'] = $application->merchant;
            $data['lender_id'] = $application->lender_id;
            $data['application_element'] = $application->application_element;
            $data['application_id'] = $id;
            $data['emi_generate'] = 1;
            $data['state'] = $application->state;
            $data['merchants'] = Merchant::with('merchant_category_many')->get(['id', 'merchant_name', 'category_id','insurance_premium']);
            $data['withHold'] = LiabilityLog::where('application_id', $id)->orderBy('created_at', 'desc')->first(['liability_percent']);
            $data['FLDGCategory'] = FLDGCategory::where('merchant_id', $application->merchant->id)->get(['id','name','available_exposure']);;
            $data['is_avanse_enabled'] = in_array($application->merchant_id , AvanseProcesses::activatedMerchants()) ? 1 : 0;
            $data['phase'] = $total_phases;
            $data['risk_based_interest_rate'] = RiskBasedInterestRate::where('application_id', $id)->orderBy('created_at', 'desc')->first(['id', 'new_interest_rate', 'is_excluding_pf', 'offer_id']);

            return view('admin.emi.index', $data);
        }

        \Session::flash('error', 'Merchant is not linked!');
        return redirect()->back();
    }

    public function applicationRejectOnly($id)
    {
        // dd("hii");
        $status = Input::get('state');

        \App\ConsumerApplication::where('id', $id)
            ->update(['state' => $status]);

        StatusLogs::insert([
            'application_id' => $id,
            'user_id' => Auth::user()->id,
            'status' => $status,
            'reason' => Input::has('abort_reason') ? Input::get('abort_reason') : (Input::has('rejection_reason') ? Input::get('rejection_reason') : ''),
            'created_at' => Carbon::now()->toDateTimeString()
        ]);

        if (_env('WHATSAPP_STATUS_AND_COMMENT')){
            try {
                $groupNotificationStatuses = ['rejected'];
                if (in_array(strtolower($status), $groupNotificationStatuses)) {
                    (new ServiceController(new Request()))->sendGroupStatusNotification($id, $status);
                }
            } catch (\Exception $e) {
                (new Slack(new Request(['title' => 'Whatsapp notification sending on status change failed', 'fields' => ['e' => $e->getMessage(),'l' => $e->getLine(),'t' => $e->getTraceAsString(), 'id' => $id], 'group' => Slack::$STAGE_TESTING])))->send();
            }
        }

        $communication = 1;
        if(Auth::check() && in_array(Auth::user()->lender_id, [AvanseServices::$lender_id, Services::$lender_id]) && $status == 'rejected'){
            $communication = 0;

            $application = ConsumerApplication::with('lender', 'merchant')->where('id', $id)->first(['id','merchant_id','name', 'lender_id']);

            \App\ConsumerApplication::where('id', $id)
                ->update(['state' => 'cf approved','lender_id' => 2]);

            StatusLogs::insert([
                'application_id' => $id,
                'user_id' => Auth::user()->id,
                'status' => 'cf approved',
                'reason' => '',
                'created_at' => Carbon::now()->toDateTimeString()
            ]);

            $userRo = User::where('id', 519)->first(['slack_id']); //rohit
            if(isset($userRo->slack_id) && $userRo->slack_id) {
                (new Slack(new Request(['title' => 'Case Rejected By ' . $application->lender->name,
                    'fields' => ['Application ID' => $id, 'Name' => ucwords($application->name), 'Merchant Name' => $application->merchant->merchant_name,
                        'Rejected By' => Auth::user()->name], 'group' => 'loan_application', 'tagging' => [$userRo->slack_id]])))->send();
            }
        }else if ($status == 'rejected'){
            if (!isset($application)){
                $application = ConsumerApplication::where('id', $id)->first(['id','merchant_id']);
            }
            $this->webhook($id, ['merchant_id' => $application->merchant_id, 'type' => 'Application-Webhook', 'status' => $status, 'data' => $this->getMConnectPayload($id, $status, ['reason' => Input::has('rejection_reason') ? Input::get('rejection_reason') : '', 'applicant_type' => 1])]);
        }

        if($communication) {
            if (Input::has('rejection_reason') && Input::get('rejection_reason')) {
                $comment = 'Rejection Reason: ' . Input::get('rejection_reason');
                saveComment($comment, $id, Auth::user()->id);
            }

            if ($status == 'rejected' || $status == 'aborted') {
                $this->sendMessageToMerchant($status, $id);
                if ($status == 'rejected') {
                    $this->insertIntoJob($id, 'referral_communication', $status);
                }
            }
        }

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

    public function updateFLDG($id, $application){
        $payload[] = [
            'payload' => json_encode(['id' => $id, 'merchant_id' => $application->merchant_id]),
            'from' => 'fldg_update',
            'application_id' => $id,
            'available_at' => Carbon::now()->toDateTimeString(),
            'created_at' => Carbon::now()->toDateTimeString()
        ];

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

    public function checkCategoryValidation($application){
        $lender_id = Input::get('lender_id') ?? $application->lender_id;
        $approved_amount = Input::get('amount') ?? $application->approved_amount;
        $lenderCategoryValidation = LenderCategoryValidation::where('category_id', $application->purpose)->where('lender_id', $lender_id)->first();
        if(isset($lenderCategoryValidation->id)){
            $remaining_emi = 0;
            if(!$application->emi){
                $emi = ApplicationEMICalculation::where('application_id', $application->id)->first(['remaining_emi']);
                if(isset($emi->remaining_emi)){
                    $remaining_emi = $emi->remaining_emi;
                }
            }else{
                $remaining_emi = $application->emi->remaining_emi;
            }
            if($remaining_emi > $lenderCategoryValidation->max_net_tenure){
                $lender = Lenders::where('id', $lender_id)->first(['name']);
                return "Tenure is above ".$lenderCategoryValidation->max_net_tenure." months cannot be pushed to ".$lender->name;
            }else if($approved_amount > $lenderCategoryValidation->max_approved_amount){
                $lender = Lenders::where('id', $lender_id)->first(['name']);
                return "Approved amount is above ".$lenderCategoryValidation->max_approved_amount." cannot be pushed to ".$lender->name;
            }
        }

        return false;
    }

    public function updateApplicationApproved($id){

        $change_status = Input::get('state');
        //if (Input::get('lender_id') != 2){
            //$change_status = 'cf approved';
        //}
        if (Input::has('amount')) {
            $consumerApplication = ConsumerApplication::with('merchant')->where('id', $id)->first(['id', 'merchant_id','approved_amount']);
            $consumerApplication = ConsumerApplication::with('merchant')->where('id', $id)->first(['id', 'merchant_id','approved_amount', 'lender_id', 'purpose']);

            if($validationMessage = $this->checkCategoryValidation($consumerApplication)){
                $data['message'] = $validationMessage;
                $data['status'] = 'FAIL';
                return response()->json($data, 200);
            }


            if($this->isMultiLender($consumerApplication->merchant_id) > 1){
                $change_status = 'cf approved';
                $this->isMultiLender = true;
            }
            $prev_app_status = ContentLogger::where('application_id', $id)->where('status',$change_status)->count();
            $total = DB::table('consumer_application')->select(DB::raw('SUM(approved_amount) as total_approved_amount'))->where('merchant_id', $consumerApplication->merchant_id)->whereIn('state', ['approved', 'disbursement checklist done','ready for disbursement','disbursed','nach registered','closed'])->first();
            $total_remaining_amount = $consumerApplication->merchant->max_approval_value - $total->total_approved_amount;
            if($consumerApplication->merchant->status == "active" && $consumerApplication->merchant->pre_status == 1 && Input::get('amount') > $total_remaining_amount && $prev_app_status < 1) {
                $data['message'] = 'Total value of approved cases or total no. of approved cases is higher than the mentioned limit. Please increase the limit and then try to change the Status';
                $data['status'] = 'FAIL';
            }else{
                $application = ConsumerApplication::with('category', 'merchant', 'activeOffer', 'emi')->where('id', $id)->first();
                $canApprove = true;
                $userApprovalLimit = User::where('id',Auth::user()->id)->whereNull('deleted_at')->first(['credit_approval_limit', 'high_risk']);
                if($userApprovalLimit){
                    if($userApprovalLimit->credit_approval_limit){
                        // when approval limit is greater than zero
                        $offer_details = MerchantOffers::where('id', $application->offer_id)->first();
                        $net_loan_amount = (new FrontController())->checkNetLoanAmount($offer_details, Input::get('amount'));
                        $canApprove = $net_loan_amount <= $userApprovalLimit->credit_approval_limit;
                    }
                }
                if (!$canApprove){
                    $data['message'] = 'You are trying to approve a case that exceeds your credit approval limit';
                    $data['status'] = 'FAIL';
                    return response()->json($data, 200);
                }
                if (Input::get('is_check') == 1){
                    if ($userApprovalLimit->high_risk && $application->merchant->vulnerable_merchant){
                        $data['message'] = 'You are trying to approve a case which is at High Risk';
                        $data['status'] = 'FAIL';
                        return response()->json($data, 200);
                    }
                }
                ConsumerApplication::where('id', $id)->update(['approved_amount' => Input::get('amount'), 'lender_id' => Input::get('lender_id')]);
                if(Input::get('risk_category')!= null){
                    ConsumerApplicationElement::where('application_id', $id)->update(['risk_category' => Input::get('risk_category')]);
                }
                // $change_status = 'approved';
                // if (Input::get('lender_id') != 2){
                //    $change_status = 'cf approved';
                // }
                $proforma = ProFormaInvoice::where('application_id', $id)->first();
                if (!isset($proforma->id)) {
                    $proforma = new ProFormaInvoice();
                    $proforma->application_id = $id;
                }
                if($application && $application->merchant && $application->merchant->collect_advance_amount){
                    $proforma->merchant_collected_advance_amount = 1;
                }else{
                    $proforma->merchant_collected_advance_amount = 0;
                }
                $proforma->fldg_applied = Input::get('fldg_applied');
                $proforma->liability_hold = Input::get('liability_hold');
                $proforma->fldg_applied_category = Input::get('fldg_applied_category');
                $proforma->insurance_premium_applicable = Input::get('insurance_premium');
                $proforma->insurance_premium_amount = Input::get('insurance_amount');
                $merchantInsuranceConfig = (new AccountingController())->getMerchantInsuranceConfig($id);
                $proforma->insurance_premium_by_merchant = $merchantInsuranceConfig['insurance_premium_by_merchant'];
                $proforma->insurance_premium_applicable = $merchantInsuranceConfig['insurance_premium_applicable'];
                $proforma->insurance_coverage = $merchantInsuranceConfig['insurance_coverage'];
                $proforma->processing_fee_by_merchant = $merchantInsuranceConfig['processing_fee_by_merchant'];
                if (!isset($proforma->loan_application_no)){
                    $loan_application_no = $this->getLoanApplicationID($id, $application->merchant);
                    $proforma->loan_application_no = isset($loan_application_no) ? $loan_application_no : null;
                }
                $proforma->save();

                if (Input::get('fldg_applied') && Input::get('fldg_applied_category')) {
                    $this->updateFLDG($id, $application);
                }

                if(Input::get('liability_hold') && Input::get('fldg_applied_category')){
                    $this->saveLiabilityPercent($application, $id);
                }

                if (Input::get('liability_percent')) {
                    $this->saveLiabilityPercent($application, $id);
                }

                if (Input::get('decision_reason')) {
                    $this->saveDecisionReason($id, Input::get('decision_reason'), Input::get('decision_reason_other'));
                }

                (new RiskController(new Request()))->riskBasedCalculationSavingValidation($id);

                if (Input::has('first_emi_date')) {
                    $request = new Request();
                    $offer = MerchantOffers::where('id', $application->offer_id)->first(['interest_type_id']);
                    $request->request->add(
                        [
                            'first_emi_date' => Input::get('first_emi_date'),
                            'loan_amount' => Input::get('amount'),
                            'merchant_id' => $application->merchant_id,
                            'category_id' => $application->category->id,
                            'interest_type_id' => $offer->interest_type_id,
                            'merchant_offer_id' => $application->offer_id,
                            'risk_based_interest_rate_excluding_pf' => Input::get('risk_based_interest_rate_excluding_pf'),
                            'gross_roi' => Input::get('gross_roi'),
                            'is_new_interest_rate_enable' => Input::get('is_new_interest_rate_enable'),
                            'new_interest_rate_after_change' => Input::get('new_interest_rate_after_change')
                        ]
                    );
                    $this->generateEMI($request, $application, $id);
                    if (Input::has('app_type') && Input::get('app_type') == 1) {
                        $this->auto_approved_status = true;
                        $this->updateApplicationStatus($id, $change_status);
                    }
                }

                $data['message'] = 'Approved Amount added in application';
                $data['status'] = 'OK';
            }
        } else {
            $data['message'] = 'Something went wrong';
            $data['status'] = 'FAIL';
        }
        return response()->json($data, 200);
    }

    public function saveDecisionReason($id, $decision_reason, $decision_reason_other)
    {
        $reason = ($decision_reason == 14 && $decision_reason_other)
            ? $decision_reason_other
            : $this->decision_reason_list[$decision_reason] ?? 'Unknown';

        if($reason) {
            $element = ConsumerApplicationElement::where('application_id', $id)->first();

            $data = [
                'application_id' => $id,
                'decision_reason' => $decision_reason,
                'decision_reason_other' => ($decision_reason == 14) ? $decision_reason_other : null,
            ];

            if ($element) {
                ConsumerApplicationElement::where('application_id', $id)->update($data);
            } else {
                $data['created_at'] = now()->toDateTimeString();
                ConsumerApplicationElement::create($data);
            }

            saveComment(
                'Other Lender Rejection Reason: ' . $reason,
                $id,
                Auth::id() ?? 107
            );
        }
    }

    public function saveLastEMIDate($id, $last_emi_date){
        $elementId = ConsumerApplicationElement::where('application_id', $id)->first(['id']);
        if(!isset($elementId->id)) {
            $consumerApplicationElement = new ConsumerApplicationElement();
            $consumerApplicationElement->application_id = $id;
            $consumerApplicationElement->last_emi_date = $last_emi_date;
            $consumerApplicationElement->created_at = Carbon::now()->toDateTimeString();
            $consumerApplicationElement->save();
        }else{
            ConsumerApplicationElement::where('application_id', $id)->update(['last_emi_date' => $last_emi_date]);
        }
    }

    private function getRequestParam($request, $key, $default = null){
       return $request->has($key) && $request->get($key) ? $request->get($key) : (isset($request->request) && $request->request->has($key) && $request->request->get($key) >= 0 ? $request->request->get($key) : $default);
    }

    public function generateEMI(Request $request, $application, $id){
        $request->request->add(array('application_id' => $id));
        $emiCalculation = new \App\Http\Controllers\Admin\EMICalculation($request);
        $emiDate = ($request->has('first_emi_date') && !empty($request->get('first_emi_date'))) ? $request->get('first_emi_date') : ($request->request->has('first_emi_date') && !empty($request->request->get('first_emi_date')) ? $request->request->get('first_emi_date') : '');
        $user_id = ($request->has('user_id') && !empty($request->get('user_id'))) ? $request->get('user_id') : ($request->request->has('user_id') && !empty($request->request->get('user_id')) ? $request->request->get('user_id') : '');
        $emi = $emiCalculation->prepareCalculation();


        $emiDetails = $emi->getData();

        $new_interest_rate_after_change = $this->getRequestParam($request, 'new_interest_rate_after_change', $emiDetails->flat_annual_interest);
        $risk_based_interest_rate_excluding_pf = $this->getRequestParam($request, 'risk_based_interest_rate_excluding_pf');
        $gross_roi = $this->getRequestParam($request, 'gross_roi');
        $is_new_interest_rate_enable = $this->getRequestParam($request, 'is_new_interest_rate_enable');


        $request = new Request();

        if($emiDetails->emi_remaining){
            $last_emi_date = Carbon::now()->addMonths($emiDetails->emi_remaining)->toDateString();
            $this->saveLastEMIDate($id, $last_emi_date);
        }

        $data = ['advance_emi' => $emiDetails->advance_emi,
            'emi' => $emiDetails->emi,
            'user_id' => $user_id,
            'first_emi_date' => ($emiDate) ? $emiDate : Input::get('first_emi_date'),
            'interest_rate' => $emiDetails->flat_annual_interest,
            'offer_id' => $emiDetails->id,
            'payable_by_customer' => $emiDetails->payable,
            'processing_fee' => $emiDetails->processing_fee,
            'received_by_merchant' => $emiDetails->total_amount_received_by_merchant,
            'remaining_emi' => $emiDetails->emi_remaining,
            'subvention' => $emiDetails->subvention,
            'tenure' => $emiDetails->total_emi,
            'upfront_from_credit_fair' => $emiDetails->up_front_from_credit_fair,
            'upfront_from_customer' => $emiDetails->up_front_from_customer,
            'subvention_cgst' => $emiDetails->subvention_cgst,
            'subvention_sgst' => $emiDetails->subvention_sgst,
            'subvention_igst' => $emiDetails->subvention_igst,
            'payment_frequency' => $emiDetails->payment_frequency,
            'disbursement_method' => $emiDetails->disbursement_method,
            'net_loan_amount' => $emiDetails->net_loan_amount,
            'legal_charges' => $emiDetails->legal_charges,
            'new_interest_rate_after_change' =>  $new_interest_rate_after_change,
            'risk_based_interest_rate_excluding_pf' => $risk_based_interest_rate_excluding_pf,
            'gross_roi' => $gross_roi,
            'is_new_interest_rate_enable' => $is_new_interest_rate_enable
        ];
        $request->request->add($data);
        $emiCalculation = new \App\Http\Controllers\Admin\EMICalculation($request);
        $emiCalculation->generateEMI($request, $id);
    }

    public function sendMessageToMerchant($type, $application_id, $auth_user_id = false){
        try {
            $application = ConsumerApplication::with('advisor', 'merchant', 'application_element.merchant_center')->where('id', $application_id)->first();
            $isCoAppRequired = 0;
            if (isset($application->application_element) && ($application->application_element->co_applicant_for_signing == 1 || $application->application_element->co_applicant_for_income == 1)) {
                $isCoAppRequired = 1;
            }
            if ($application->merchant_id != 21 && (!in_array($application->merchant_id, explode(',', _env('NO_COMM_MERCHANT'))))) {
                $merchantData = [
                    'merchant_name' => isset($application->merchant->merchant_name) ? $application->merchant->merchant_name : '',
                    'applicant_name' => $application->name,
                    'subject' => ($isCoAppRequired) ? "We can’t approve $application->name's application  of Rs $application->loan_amount, please add co-applicant" : 'Thanks for your loan application',
                    'to' => isset($application->merchant->email) ? explode(',', $application->merchant->email) : '',
                    'phone' => isset($application->merchant->contact_number) ? $application->merchant->contact_number : '',
                    'isCoAppRequired' => $isCoAppRequired,
                    'loan_amount' => $application->loan_amount
                ];
                $cc_emails = [];
                $phones = [];
                if (isset($application->application_element) && isset($application->application_element->merchant_center)) {
                    if (isset($application->application_element->merchant_center->email)) {
                        $cc_emails[] = $application->application_element->merchant_center->email;
                    }
                    if (isset($application->application_element->merchant_center->phone)) {
                        $phones[] = $application->application_element->merchant_center->phone;
                    }
                }
                if ($merchantData['phone']) {
                    if ($type == 'rejected') {
                        if ($isCoAppRequired) {
                            $sms = "Dear " . $merchantData['merchant_name'] . ", We cannot approve " . $merchantData['applicant_name'] . "'s application of Rs " . $merchantData['loan_amount'] . " based on current documents. Please add a co-applicant with<br/>1) Income Proof<br/>2) Bank Statement<br/>3) Salary Slip<br/>4) ITR<br/><br/>If a co-applicant isn't available, we'd be happy to reconsider them after 3 months. <br/>Regards,<br/>Team Credit Fair<br/>ops@creditfair.in<br/>+91-9967235047";
                            if ($application->advisor && $application->advisor->mobile_number) {
                                sendWhatsAppMessage($application->advisor->mobile_number, $sms);
                            }
                        } else {
//                            $sms = "Dear " . $merchantData['merchant_name'] . ",<br/>We regret to inform you that we cannot approve " . $merchantData['applicant_name'] . " request at this time. We'd be happy to reconsider them after 3 months. If you have any questions about our decision, please free to contact at +91-9967235047.<br/>Regards,<br/>Team Credit Fair";
                            $sms = "Dear " . $merchantData['merchant_name'] . ", <br/>We are sorry to inform you that we cannot proceed ahead with " . $merchantData['applicant_name'] . "'s loan application. We’d be happy to reconsider the case after 3 months. <br/> - Credit Fair";
                            $entity = ['templateid' => '1307166902803546695', 'entityid' => Templates::$entityid];
                            $templateId = Templates::$rejection_c1;
                            $args = [$merchantData['merchant_name'], $merchantData['applicant_name']];
                            try {
                                if ($templateData = $this->getPreferredLanguageTemplate($application, $merchantData, $type, 'merchant')) {
                                    $sms = $templateData['sms'];
                                    $templateId = $templateData['templateId'];
                                    $args = $templateData['args'];
                                }
                            }catch (\Exception $e){

                            }
                        }
                    } else {
                        $abort_reason_message = '';
                        $abort_reason = '';
                        if (Input::has('abort_reason')) {
                            $abort_reason = Input::has('abort_reason') ? Input::get('abort_reason') : '';
                            if ($abort_reason) {
                                $abort_reason_message = 'as ' . $abort_reason;
                            }
                        }
                        $merchantData['abort_reason_message'] = $abort_reason_message;
//                        $sms = "Dear " . $merchantData['merchant_name'] . ",<br/>We wanted to update you on the status of " . $merchantData['applicant_name'] . "'s loan application. The application has aborted by the customer $abort_reason_message.<br/>Please contact the customer or us at +91-9967235047 if there has been an error.<br/>Regards<br/>Team Credit Fair";
                        $sms = "Dear " . $merchantData['merchant_name'] . ",<br/> we would like to inform you that we have cancelled " . $merchantData['applicant_name'] .
                            "'s loan application. Kindly contact them or connect with us at 9967235047 in case of any query. <br/> - Credit Fair";
                        $entity = ['templateid' => '1307166902816938449', 'entityid' => Templates::$entityid];
                        $templateId = Templates::$cancelled_c1;
                        $args = array_filter([$merchantData['merchant_name'], $merchantData['applicant_name']]);
                        $merchantData['abort_reason_message'] = $abort_reason_message;
                        try {
                            if ($templateData = $this->getPreferredLanguageTemplate($application, $merchantData, $type, 'merchant')) {
                                $sms = $templateData['sms'];
                                $templateId = $templateData['templateId'];
                                $args = $templateData['args'];
                            }
                        }catch (\Exception $e){

                        }
                        $abort_reason = $abort_reason ? $abort_reason : ' we haven’t heard from them';
                        if($abort_reason == "Demo Login"){
                            $merchantData['subject'] = 'We are canceling ' . $merchantData['applicant_name'] . '\'s application since it was a Demo application';
                        }else{
                            $merchantData['subject'] = 'We are canceling ' . $merchantData['applicant_name'] . '\'s application since ' . $abort_reason;
                        }
                        if(!$auth_user_id) {
                            Comments::insert([
                                'application_id' => $application_id,
                                'user_id' => 0,
                                'comment' => 'This case was auto-aborted because we haven\'t heard from the customer.',
                                'show_consumer' => 0,
                                'show_merchant' => 0,
                                'created_at' => Carbon::now()->toDateTimeString(),
                                'updated_at' => Carbon::now()->toDateTimeString(),
                                'type' => 'consumer'

                            ]);
                        }
                    }
                    // array_push($phones, $merchantData['phone']);
                    // $phones = array_unique(array_filter($phones));
                    // send_sms(implode(',', $phones), ['message' => $sms, 'id' => $application_id, 'id_type' => 'application_id', 'templateId' => $templateId, 'args' => $args, 'templateDetails' => $entity]);
                }
                //$_cc_email = $type == 'rejected' ? 'ops@creditfair.in' : 'centralops@creditfair.in';
                // $_cc_email = 'centralops@creditfair.in';
                if ($merchantData['to']) {
                    \Mail::send('emails.reminders.merchant_for_' . $type, [
                        'data' => $merchantData,
                    ], function ($message) use ($merchantData, $cc_emails,  $type) {
                        if ($type == 'rejected') {
                            //$message->from(env('CENTRALOPS'));
                        }
                        $message->bcc(_env('BACKUP_EMAIL'));
                        $message->to($merchantData['to'])->subject($merchantData['subject']);
                        // array_push($cc_emails);
                        $cc_emails = array_unique($cc_emails);
                        if ($cc_emails) {
                            $message->cc($cc_emails);
                        }
                    });
                }
            }
        } catch (\Exception $exception) {
        }
    }

    public function updateAdvisor($application_id){
        $consumer_application = ConsumerApplication::where('id', $application_id)->first(['created_by']);
        if ($consumer_application->created_by == 0 || $consumer_application->created_by == null) {
            $user = Auth::user() ? Auth::user()->id : Input::get('auth_user_id');
            if ($user) {
                ConsumerApplication::where('id', $application_id)
                    ->update(['created_by' => $user]);
            }
        }
    }

    public function getPreferredLanguageTemplate($application, $data, $status, $type){
        try {
            if(isset($pp) && isset($application->application_element) && isset($application->application_element->preferred_language) && $application->application_element->preferred_language == 'HINDI') {
                if ($status == 'rejected' && $type == 'merchant') {
                    $sms = "Dear " . $data['merchant_name'] . ",<br/> आपके Client " . $data['applicant_name'] . " का  Loan Application अप्प्रोवे नहीं कर सकते हम उनका Loan application का आवेदन ३ महीने बाद फिरसे ले सकते है. <br/>Best Regards,<br>Team Credit Fair";
                    return ['sms' => $sms, 'args' => [$data['merchant_name'], $data['applicant_name']], 'templateId' => 'rejected_merchant_preferred'];
                } elseif ($status == 'rejected' && $type == 'customer') {
                    $sms = "Dear " . $application->name . ",हम आपका Loan Application of Rs." . $application->loan_amount . " अप्प्रोवे नहीं कर सकते आप ३ महीने बाद अपना Loan application आवेदन फिरसे दे सकते है.<br/>Best Regards,<br/>Team Credit Fair";
                    return ['sms' => $sms, 'args' => [$application->name, $application->loan_amount], 'templateId' => 'rejected_customer_preferred'];
                } elseif ($status == 'aborted' && $type == 'merchant') {
                    $sms = "Dear " . $data['merchant_name'] . ",<br/> आपके Client " . $data['applicant_name'] . " का  Loan Application " . $data['abort_reason_message'] . " के कारन कैंसिल कर दिया गया है. <br/>Best Regards,<br/>Team Credit Fair";
                    return ['sms' => $sms, 'args' => [$data['merchant_name'], $data['applicant_name'], $data['abort_reason_message']], 'templateId' => 'aborted_merchant_preferred'];
                } elseif ($status == 'approved' && $type == 'customer') {
                    $sms = "Dear " . $application['name'] . ",<br/> आपका Loan Application " . $data['loan_application_no'] . " for परचेस from " . $application['merchant']['merchant_name'] . " अप्प्रोवे हो गया है कृप्या अपना sanction letter एक्सेप्ट करे और यह लिंक पर जाकर प्रोसेस complete करे<br/>Best Regards,<br/>Team Credit Fair";
                    return ['sms' => $sms, 'args' => [$application['name'], $data['loan_application_no'], $application['merchant']['merchant_name'], $data['link']], 'templateId' => 'approved_customer_preferred'];
                } elseif ($status == 'approved' && $type == 'merchant') {
                    $sms = "Dear " . $application['merchant']['merchant_name'] . ",<br/> कृप्या Disbursement advice of " . $application['name'] . " एक्सेप्ट करे और हमें निचे दिए गए documents वापस भेजे <br/>Best Regards,<br/>Team Credit Fair";
                    return ['sms' => $sms, 'args' => [$application['merchant']['merchant_name'], $application['name']], 'templateId' => 'approved_merchant_preferred'];
                }
            }
        }catch (\Exception $e){
            return false;
        }
    }

    public function updateSystemReminders($application_id){
        return false;
        $user_id = Auth::user() ? Auth::user()->id : Input::get('auth_user_id');
        if($user_id) {
            $app_reminder = JobProvider::where('application_id', $application_id)->where('from', 'app_reminder')->where('payload', 'like', '%more_than_2_days_reminder%')->first(['id']);
            if (isset($app_reminder->id)) {
                JobProvider::where('id', $app_reminder->id)->delete();
            }
            $payload = [
                'payload' => json_encode(['status' => 'more_than_2_days_reminder', 'comment_id' => 0, 'auth_user_id' => $user_id]),
                'from' => 'app_reminder',
                'application_id' => $application_id,
                'available_at' => Carbon::now()->addDay(3)->toDateTimeString(),
                'created_at' => Carbon::now()->toDateTimeString()
            ];
            JobProvider::insert($payload);
        }
    }

    public function insertIntoJob($application_id, $type, $status){
        switch ($type) {
            case 'referral_communication':
                return $this->$type($application_id, $type, $status);
                break;
            default:
                break;
        }
    }

    public function disbursementAnalysis($application_id){
        $applicationLoggedIn = StatusLogs::where('application_id', $application_id)->orderBy('created_at','asc')->first(['created_at']);
        if(isset($applicationLoggedIn->created_at) && $applicationLoggedIn->created_at) {
            $hour = Carbon::now()->diffInHours($applicationLoggedIn->created_at);
            if($hour < 36){
                $days = Carbon::now()->diffInDays($applicationLoggedIn->created_at);
                $time_string = $hour == 1 ? $hour.' Hour' : $hour.' Hours';
                if($days){
                    $time_string_day = $days == 1 ? $days.' Day ' : $days.' Days ';
                    $time_string = $time_string_day.$time_string;
                }
                $application = ConsumerApplication::with('merchant')->where('id',$application_id)->first();
                if(isset($application->merchant)){
                    $emails = [];
                    $application_element = ConsumerApplicationElement::where('application_id', $application_id)->first(['merchant_representative_name', 'merchant_representative_mobile', 'merchant_representative_email']);
                    if($application->merchant->rcp_email){
                        $emails[] = ['name' => $application->merchant->rcp, 'email' => $application->merchant->rcp_email, 'mobile' => $application->merchant->rcp_mobile];
                    }
                    if($application->merchant->sales_head_email){
                        $emails[] = ['name' => $application->merchant->sales_head, 'email' => $application->merchant->sales_head_email, 'mobile' => $application->merchant->sales_head_mobile];
                    }
                    if($application_element && $application_element->merchant_representative_email){
                        $emails[] = ['name' => $application_element->merchant_representative_name, 'email' => $application_element->merchant_representative_email, 'mobile' => $application_element->merchant_representative_mobile];
                    }
                    if($emails) {
                        foreach($emails as $email) {
                            $name = ucfirst(strtolower($email['name']));
                            $message_body = "Dear $name,<br/><br/>

Congratulations! Disbursement for $application->name was done in just $time_string .<br/><br/>

We told you, we believe in providing not just FAIR Finance to everyone, but also QUICK finance facility that helps you serve your customer in the best possible way. Apart from disbursing 365 days, we are now open to lightning speed disbursals which could take around 2 days for your customer's loan payment to get credited to your account.<br/><br/>

Sounds too much?<br/><br/>

We suggest, why not try us now?<br/><br/>

Send us a lead/ an application and we will revert quickly. No longer than 2 days, we promise!<br/><br/>

Regards,<br/>

Credit Fair- Operations<br/>";
                            Mail::send('emails.reminders.basic_reminder',
                                ['body' => $message_body]
                                , function ($message) use ($name, $email) {
                                    $message->to($email['email'])->subject($name.', Lightning fast disbursals just for you!');
                                    $message->cc('centralOps@creditfair.in');
                            });
                            if($email['mobile']){
                                $message = "Dear ".$name.",<br/> congratulations! Loan of ".$application->name." was disbursed in just ".$time_string.".<br/> We are now disbursing loans at lighting speed. Don't believe it? Try us again<br/><br/> - Credit Fair";
                                $entity = ['templateid' => '1307166902848546479', 'entityid' => Templates::$entityid];
                                send_sms($email['mobile'], ['message' => $message, 'id' => $application_id, 'id_type' => 'application_id', 'templateId' => Templates::$lightning_disbursed_merchant_represntative, 'args' => [$name, $application->name, $time_string], 'templateDetails' => $entity]);
                            }
                        }
                    }
                }
            }
        }
    }

    public function tradeAdvanceDisbursement($id, $documentDetails){
        if((new TradeAdvanceDisbursement())->getBalanceAmount($documentDetails['user']['merchant_id'], $documentDetails['netdisbusedamount']) > 0) {
            $tradeAdvanceDisbursement = TradeAdvanceDisbursement::where('application_id', $id)->first(['id']);
            if (!isset($tradeAdvanceDisbursement->id)) {
                TradeAdvanceDisbursement::insert([
                    'application_id' => $id,
                    'merchant_id' => $documentDetails['user']['merchant_id'],
                    'net_amount' => $documentDetails['netdisbusedamount']
                ]);
            }
        }
    }

    public function sendCFApprovedCommunication($application){
        $merchant = Merchant::where('id', $application->merchant_id)->first(['id','merchant_name']);
        $sms = "Dear ".$application->name.",<br/> We are happy to inform you that your loan has been approved for an amount of Rs ".$application->approved_amount." towards your purchase at ".$merchant->merchant_name.". Track your application on our app https://bit.ly/2HQO1EX.<br/> - Credit Fair";
        $entity = ['templateid' => '1307166902843784100', 'entityid' => Templates::$entityid];
        send_sms($application->mobile_number, ['message' => $sms, 'id' => $application->id, 'id_type' => 'application_id', 'templateId' => Templates::$cf_approved, 'args' => [$application->name, $application->approved_amount, $merchant->merchant_name], 'templateDetails' => $entity]);
    }

    public function sendSoftApprovalCommunication($application){
        // $_body = "Dear ".$application->name.",<br><br> Congrats! Your loan up to Rs.".$application->approved_amount." is soft approved, subject to final checks. Kindly note that the loan offer may change depending on your credit profile.";
        // $customer_email = $application->email;
        // $customer_mobile =  $application->mobile_number;
        // if($customer_email) {
        //     Mail::send('emails.reminders.basic_reminder',
        //         ['body' => $_body]
        //         , function ($message) use ($customer_email) {
        //             $message->to($customer_email)->subject('Congrats ! Your loan is soft approved');
        //         });
        // }
        // if($customer_mobile) {
        //     $sms = "Congrats ! Your loan is soft approved. Dear ".$application->name.", Congrats! Your loan up to Rs.".$application->approved_amount." is soft approved, subject to final checks. Kindly note that the loan offer may change depending on your credit profile. Regards, Team CreditFair";
        //     $entity = ['templateid' => '1307172199894667315', 'entityid' => Templates::$entityid];
        //     send_sms($application->mobile_number, ['message' => $sms, 'id' => $application->id, 'id_type' => 'application_id', 'templateDetails' => $entity]);

        // }

        // if($application->merchant_id) {

        //     $_merchant = Merchant::where('id',$application->merchant_id)->first(['email', 'contact_number', 'merchant_name']);
        //     if (isset($_merchant->email) && !empty($_merchant->email)) {
        //         $email = explode(',', trim($_merchant->email));

        //         Mail::send('emails.reminders.basic_reminder',
        //             ['body' => $_body]
        //             , function ($message) use ($email) {
        //                 $message->to($email)->subject('Congrats ! Your loan is soft approved');
        //             });
        //     }
        //     if (isset($_merchant->contact_number) && !empty($_merchant->contact_number)) {
        //         $merchant_body = "Dear ".$_merchant->merchant_name.", Loan up to Rs.".$application->approved_amount." is soft approved for ".$application->name." and ".$application->id.", subject to final checks. Kindly note that the loan offer may change depending on the customers credit profile. Regards, Team CreditFair";
        //         $entity = ['templateid' => '1307172199907279574', 'entityid' => Templates::$entityid];
        //         send_sms($_merchant->contact_number, ['message' => $merchant_body, 'id' => $application->id, 'id_type' => 'application_id', 'templateDetails' => $entity]);
        //     }
        // }
        $consumerdDocument = new ConsumerDocument(new Request(['id' => $application->id]));
        $consumerdDocument->sendTermSheet();

    }

    public function sendAutoSoftApprovalCommunication($application){
        //for credit email communication
        $_merchant = optional(Merchant::find($application->merchant_id))->merchant_name ?? "";
        $advisor_name = optional(User::find($application->created_by))->name ?? "";
        $offer_details = MerchantOffers::where('id', $application->offer_id)->first();
        $net_loan_amount = (new FrontController())->checkNetLoanAmount($offer_details, $application->approved_amount);
        $credit_body = "Customer Name: ".$application->name."<br>Merchant Name: ".$_merchant."<br>Advisor Name: ".$advisor_name."<br>Application Link: <a href=".asset("admin/consumer-applications/edit/".$application->id).">Click Here</a><br>Status: CF Approved<br><br>Regards,<br>Team Credit Fair";
        $credit_manager_emails = User::wherenull('deleted_at')->wherenotnull('credit_approval_limit')->where('credit_approval_limit', '>=', $net_loan_amount)->whereIn('user_type', [_env('CREDIT_TEAM_USER_TYPE'), _env('SENIOR_CREDIT_TEAM_USER_TYPE')])->get(['email'])->pluck('email');
        if($credit_manager_emails->isNotEmpty()) {
            $credit_recipients = $credit_manager_emails->toArray();
            Mail::send('emails.reminders.basic_reminder',
                ['body' => $credit_body]
                , function ($message) use ($credit_recipients, $net_loan_amount) {
                    $message->to($credit_recipients)->subject("CF Approved Net Loan Amount ₹".$net_loan_amount);
                });
        }
        //for credit team slack notif
        $lender_name = optional(Lenders::find($application->lender_id))->name ?? "";
        try{
            (new Slack(new Request(['title' => 'New Application CF Approved', 'fields' => ['Customer Name' => $application->name,'Loan Amount'=>$net_loan_amount, 'Merchant Name'=>$_merchant, 'Application link'=>asset("admin/consumer-applications/edit/".$application->id), 'Lender'=>$lender_name], 'group' => Slack::$CRED_TEAM_SOFT_APPROVAL])))->send();
        }
        catch (\Exception $e){
            (new Slack(new Request(['title' => 'slack notif for cf approval job creation failed', 'fields' => ['e' => $e->getMessage(),'l' => $e->getLine(),'t' => $e->getTraceAsString(), 'id' => $application->id], 'group' => Slack::$STAGE_TESTING])))->send();
        }
    }

    public function whatsAppCommunication($application, $status = null){
        $user = $userData = User::where('mobile_number',$application->mobile_number)->first(['id','whatsapp_api','user_verified']);
        if(isset($application->merchant_id) && $application->merchant_id && BNPL::is($application->merchant_id)){
            return true;
        }
        $consent_key = array_search ('Rating', CommunicationService::$com_category);
        $wa_comm = CommunicationMapping::whereRaw('FIND_IN_SET('.$consent_key.',type_ids)')->where('communication_id',3)->where('merchant_id',$application->merchant_id)->count();
        $communication = CommunicationMapping::where('merchant_id',$application->merchant_id)->count();
        if($user) {
            $init = $user->whatsapp_api && $user->whatsapp_api ? $user->whatsapp_api : false;
            if (!$init) {
                $init = is_null($user->whatsapp_api) && $user->user_verified ? true : false;
            }
            if ($init && !$user->whatsapp_api) {
                User::where('id', $user->id)->update(['whatsapp_api' => 1]);
            }
            if ($init && ($wa_comm == 1 || $communication == 0) && $status != "approved") {
                $element = ConsumerApplicationElement::where('application_id', $application->id)->whereIn('preferred_language', ['HINDI','MARATHI'])->first(['id']);
                $template = Templates::$rate_service_v1;//isset($element->id) ? Templates::$rate_service_v2 : Templates::$rate_service_v1;
                $args = isset($element->id) ? ['बहुत अच्छी', 'अच्छी', 'बुरी'] : ['Excellent', 'Good', 'Not Satisfactory'];
                $templateLanguage = isset($element->id) ? 'hi' : 'en';
                sendWhatsAppMessage($application->mobile_number, ['id' => $application->id, 'templateId' => $template, 'args' => $args, 'templateType' => 'buttonTemplate', 'templateLanguage' => $templateLanguage]);
            }
        }

        if ($application->co_applicant_name && $application->co_applicant_mobile_number) {
            $user = User::where('mobile_number', $application->co_applicant_mobile_number)->first(['id','whatsapp_api','user_verified']);

            if($user) {
                $init = $user->whatsapp_api && $user->whatsapp_api ? $user->whatsapp_api : false;
                if (!$init) {
                    $init = is_null($user->whatsapp_api) && $user->user_verified ? true : false;
                }

                if ($init && !$user->whatsapp_api) {
                    User::where('id', $user->id)->update(['whatsapp_api' => 1]);
                }

                if ($init && ($wa_comm == 1 || $communication == 0) && $status != "approved") {
                    $element = ConsumerApplicationElement::where('application_id', $application->id)->whereIn('preferred_language', ['HINDI','MARATHI'])->first(['id']);
                    $template = Templates::$rate_service_v1;//isset($element->id) ? Templates::$rate_service_v2 : Templates::$rate_service_v1;
                    $args = isset($element->id) ? ['बहुत अच्छी', 'अच्छी', 'बुरी'] : ['Excellent', 'Good', 'Not Satisfactory'];
                    $templateLanguage = isset($element->id) ? 'hi' : 'en';
                    sendWhatsAppMessage($application->co_applicant_mobile_number, ['id' => $application->id, 'templateId' => $template, 'args' => $args, 'templateType' => 'buttonTemplate', 'templateLanguage' => $templateLanguage]);
                }
            }
        }
        if($status == 'approved') {
            $this->triggerMerchantWhatsAppCommunication($application, $userData);
        }else{
            $this->sendRatingWhatsAppMessageToMerchant($application);
        }
    }

    public function sendRatingWhatsAppMessageToMerchant($application){
        $application = ConsumerApplication::with('merchant')->where('id',$application->id)->first(['id','merchant_id']);
        if ($application->merchant && $application->merchant->contact_number && !in_array($application->merchant_id, explode(',', _env('NO_COMM_MERCHANT')))) {


            $user = User::where('mobile_number',$application->merchant->contact_number)->first(['id','whatsapp_api','user_verified']);
            if($user) {
                $init = $user->whatsapp_api && $user->whatsapp_api ? $user->whatsapp_api : false;
                if (!$init) {
                    $init = is_null($user->whatsapp_api) && $user->user_verified ? true : false;
                }

                if ($init && !$user->whatsapp_api) {
                    User::where('id', $user->id)->update(['whatsapp_api' => 1]);
                }

                $consent_key = array_search ('Rating', CommunicationService::$com_category);
                $wa_comm = CommunicationMapping::whereRaw('FIND_IN_SET('.$consent_key.',type_ids)')->where('communication_id',3)->where('merchant_id',$application->merchant_id)->count();
                $communication = CommunicationMapping::where('merchant_id',$application->merchant_id)->count();

                if(($init) && ($wa_comm == 1 || $communication == 0)) {
                    $user = User::where('mobile_number', $application->merchant->contact_number)->first(['id', 'whatsapp_api']);
                    if ($user && (is_null($user->whatsapp_api) || $user->whatsapp_api)) {
                        sendWhatsAppMessage($application->merchant->contact_number, ['id' => $application->id, 'templateId' => Templates::$rate_service_v1, 'args' => ['Excellent', 'Good', 'Not Satisfactory'], 'templateType' => 'buttonTemplate']);
                    }
                }
            }
        }
    }

    public function triggerMerchantWhatsAppCommunication($application, $user){

        if(isset($application->id) && isset($user->id)) {
            $payload = [
                'payload' => json_encode(['id' => $application->id, 'user_id' => $user->id]),
                'from' => 'documentUploadBot',
                'application_id' => $application->id,
                'available_at' => Carbon::now()->addDays(3)->toDateTimeString(),
                'created_at' => Carbon::now()->toDateTimeString()
            ];
            JobProvider::insert($payload);
        }
    }

    public function sendInstallmentDateMismatch(Request $request){
        (new Slack(new Request(['title' =>'First EMI Date is not same as First Installment date', 'fields' => ['Application ID' => $request->get('id'), 'Name' => $request->get('name'), 'Merchant Name' => $request->get('merchant_name'), 'Link' => $request->get('link')], 'group' => Slack::$CREDIT_DECISION])))->send();
    }

    public function documentUploadBot(Request $request){

        $user = User::where('id',$request->get('user_id'))->first(['id','whatsapp_api','user_verified']);
        $application = ConsumerApplication::where('id',$request->get('id'))->first(['name','mobile_number','state']);

        if($user && isset($application->state) && strtolower($application->state) == 'approved') {
            $init = $user->whatsapp_api && $user->whatsapp_api ? $user->whatsapp_api : false;
            if($init){
                $args = [$application->name, 'https://bit.ly/33UhWD2'];
                sendWhatsAppMessage($application->mobile_number, ['id' => $application->id, 'templateId' => Templates::$document_message_bot, 'args' => $args, 'templateTypeSystem' => true]);
            }
        }
    }

    public function referral_communication($application_id, $type, $status = '')
    {
        $application = ConsumerApplication::where('id', $application_id)->first(['merchant_id']);
        if (isset($application->merchant_id) && $application->merchant_id > 0) {
            $applicationApplicationCount = ConsumerApplication::where('merchant_id', $application->merchant_id)->count();
            if ($applicationApplicationCount == 1) {

                $app = ConsumerApplication::where('merchant_id', $application->merchant_id)->first();
                $_status = ($status == 'approved') ? 'rejected' : 'approved';
                $statusLog = StatusLogs::where('application_id', $app->id)->where('status', $_status)->first();
                if (!isset($statusLog->id)) {
                    $merchant = Merchant::where('id', $application->merchant_id)->first(['referred_by']);
                    $user = User::where('code', $merchant->referred_by)->first(['id']);
                    if (isset($user->id)) {
                        $payload[] = [
                            'payload' => json_encode(['user_id' => $user->id, 'type' => $type]),
                            'from' => 'basic_communication',
                            'application_id' => $application_id,
                            'available_at' => Carbon::now()->toDateTimeString(),
                            'created_at' => Carbon::now()->toDateTimeString()
                        ];

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

    public function hardBureauPullForRfd($application_id){
        $application = ConsumerApplication::where("id",$application_id)->first(['id','co_applicant_name']);
        $credit_report = CreditReport::where('application_id', $application_id)
                                                ->where('applicant_type', 1)
                                                ->where('bureau_type',0)
                                                ->whereNull('deleted_at')
                                                ->first();
        $status = "OK";
        $message = "";            
        $credit_report_doc = ConsumerApplicationFiles::where([
            ['consumer_application_id', $application_id],
            ['file_type', 'equifax_report']])->exists();
        $file_path = $application_id.'/'.$application_id.'_response_experian.json';
        $s3 = Storage::disk('s3');
        if (!isset($credit_report->id) && !$credit_report_doc && !$s3->exists($file_path)) {
            $app_bureau_response = $this->generateEqifaxReport($application_id, $type = 'customer', $only_bureau = true);
            if((isset($app_bureau_response['status']) && $app_bureau_response['status'] == "FAIL") || 
               (isset($app_bureau_response->status) && $app_bureau_response->status == "FAIL") || 
               empty($app_bureau_response)) {
                    $status = "FAIL";
                    if (isset($app_bureau_response['message']) && $app_bureau_response['message']) {
                        $message = $message." ".$app_bureau_response['message'];
                    } else {
                        $message = "Failed to generate applicant hard pull bureau report";
                    }
            }
        }
        if (isset($application->co_applicant_name)) {
            $co_app_credit_report = CreditReport::where('application_id', $application_id)
                                                ->where('applicant_type', 2)
                                                ->where('bureau_type',0)
                                                ->whereNull('deleted_at')
                                                ->first();
            $coAppCreditreport = ConsumerApplicationFiles::where([
                ['consumer_application_id', $application_id],
                ['file_type', 'co_applicant_equifax_report']])->exists();
            $file_path_2 = $application_id.'/'.$application_id.'_response_2_experian.json';

            if (!isset($co_app_credit_report->id) && !$coAppCreditreport && !$s3->exists($file_path_2)) {
                $input = Input::all(); 
                    $input['applicant_type'] = 2;
                $co_app_bureau_response = $this->generateEqifaxReport($application_id, $type = 'customer', $only_bureau = true);
                if((isset($co_app_bureau_response['status']) && $co_app_bureau_response['status'] == "FAIL") || (isset($co_app_bureau_response->status) && $co_app_bureau_response->status == "FAIL") || empty($co_app_bureau_response)) {
                    $status = "FAIL";
                    if (isset($co_app_bureau_response['message']) && $co_app_bureau_response['message']) {
                        $message = $message." ".$co_app_bureau_response['message'];
                    } else {
                        $message = "Failed to generate co-applicant hard pull bureau report";
                    }
                }
            }
           
        }
        return ['status' => $status, 'message' => $message];

    }

    public function updateStatus($application_id, $insideCall = false)
    { try{
        $cwFactory = new CloudWatchLoggerFactory();
        $is_reveresed = 0;
        $user_id = Auth::user() ? Auth::user()->id : 107;
        $status = (Input::has('state') && Input::get('state')) ? Input::get('state') : $this->current_status;
        $secondaryStatus = Input::has('secondary_status') ? Input::get('secondary_status') : null;

        // caller function logged to check for incorrect auto approved cases
        try {
            $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
            $caller = $backtrace[1] ?? [];
            $callerClass = $caller['class'] ?? 'Global/Closure';
            $callerFunction = $caller['function'] ?? 'UnknownFunction';
            $calledBy = $callerClass . '::' . $callerFunction;
            (new Slack(new Request(['title' => 'Auto Decision Queue Status update', 'fields' => ['status' => $status, 'application_id' => $application_id, 'calledBy' => $calledBy]])))->send();
        } catch (Exception $e) {
            (new Slack(new Request(['title' => 'Auto Decision Queue Status update', 'fields' => ['status' => $status, 'application_id' => $application_id, 'message' => $e->getMessage(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString()]])))->send();
        }
        if (Input::has('autoDecisionQueue') && Input::get('autoDecisionQueue')) {
            (new Slack(new Request(['title' => 'Auto Decision Queue Status update', 'fields' => ['status' => $status, 'application_id' => $application_id]])))->send();
        }
        if(empty($status) && \request()->has('status') && \request()->get('status')){
            $status = \request()->get('status');
        }

        if (isset($secondaryStatus) && $secondaryStatus == 'settlement-done') {
            if (!(new AccountingController())->checkSettlementPendingVerification($application_id)) {
                return response()->json(['status' => 'FAIL','message'=>'Please clear the pending settlement verification before changing status to settlement done.'], 200);
            }
        }
        // delete the maker checker entry when settlement aborted
        if (isset($secondaryStatus) && $secondaryStatus == 'settlement-aborted') {
            \App\SettlementMakerChecker::where('application_id', $application_id)->orderBy('created_at', 'desc')->limit(1)->update(['deleted_at' => Carbon::now()->toDateTimeString()]);
        }

        // settlement reconcile call when moving to settled secondary state to create write off entries for bounce and penal
        if (isset($secondaryStatus) && $secondaryStatus == 'settled') {
            $settlementMakerChecker = \App\SettlementMakerChecker::where('application_id', $application_id)
                ->where('status', 'approved')
                ->first();
            if ($settlementMakerChecker) {
                $settlementResponse = (new AccountingController())->markSettled($settlementMakerChecker->id);
                if ($settlementResponse instanceof \Illuminate\Http\JsonResponse) {
                    $responseData = $settlementResponse->getData(true);
                    if (isset($responseData['status']) && $responseData['status'] === 'error') {
                        return response()->json(['status' => 'FAIL', 'message' => $responseData['message'] ?? 'Failed to mark settlement.'], 200);
                    }
                }
            } else {
                return response()->json(['status' => 'FAIL', 'message' => 'No approved settlement record found for this application.'], 200);
            }
        }

        if (isset($secondaryStatus) && !empty($secondaryStatus)) {
            SecondaryStatusLogs::insert([
                'application_id' => $application_id,
                'user_id' => $user_id,
                'status' => $secondaryStatus,
                'reason' => '',
                'is_reversed' => $is_reveresed,
                'created_at' => Carbon::now()->toDateTimeString()
            ]);
            ConsumerApplication::where('id', $application_id)->update(['secondary_status' => $secondaryStatus]);
            // return statement added to skip primary status change in status logs
            return response()->json(['status' => 'SUCCESS', 'message' => 'Secondary Status updated successfully']);
        }

        if($status == "" || empty($status)){
            return response()->json(['status' => 'FAIL','message'=>'Fail to update the application status'], 200);
        }

        if($this->isMultiLender){
            $status = $this->current_status;
        }

        if($status == "cf approved"){
            $this->markCommentForCoApp($application_id);
        }
        
        $application_status = ConsumerApplication::with('bank_details', 'advisor','lender','application_element','emi')->where('id', $application_id)->first(['id', 'merchant_id', 'lender_id', 'purpose', 'approved_amount', 'loan_amount', 'state', 'name', 'user_id', 'created_by', 'updated_by']);
        $previous_status = (isset($application_status->state)) ? $application_status->state : "";
        if ($previous_status == $status) { // avoid status change if status is already on current state
            return response()->json(['status' => 'SUCCESS', 'message' => 'Status is already '.$status]);
        }
        if($status == "disbursement checklist done" && $application_status->lender_id ==2 ){
            $resbureau = $this->hardBureauPullForRfd($application_status->id);
            if((isset($resbureau['status']) && $resbureau['status'] == "FAIL") || (isset($resbureau->status) && $resbureau->status == "FAIL")){
                return response()->json($resbureau, 200);
            }
        }

        if (in_array($status, ['in-process', 'waiting for documents', 'form completed', 'incomplete-form']) && !$insideCall) {
            $autodecisionCheckresponse = (new autoBRE())->checkAutoBREStatus($application_id);
            $cwFactory->logger(json_encode(["application_id" => $application_id, "title" => "autoBRE", "response" => $autodecisionCheckresponse->getData(), 'user_id'=> isset(Auth::user()->id) ? Auth::user()->id : 107]));
            if($autodecisionCheckresponse->getData() && $autodecisionCheckresponse->getData()->status == 'FAIL'){
                return $autodecisionCheckresponse;
            }
        }

        if(Input::get('state') && str_replace('+', ' ', Input::get('state')) == 'cf approved') {
            if ($validationMessage = $this->checkCategoryValidation($application_status)) {
                $data['message'] = $validationMessage;
                $data['status'] = 'FAIL';
                return response()->json($data, 200);
            }
        }


        if ($application_status->lender_id == Services::$lender_id && $status == 'approved' && !Input::get('source')){
            return response()->json(['status' => 'OK'], 200);
        }


        if ($status == 'disbursed' && $previous_status == 'nach registered'){
            (new Slack(new Request(['title' => 'Status changed', 'fields' => ['Previous Status' => $previous_status, 'Current Status' => $status, 'Customer Name' => $application_status->name, 'Lender' => $application_status->lender->name, 'application_id' => $application_id], 'group' => 'payment_collection'])))->send();
        }

        if (($status != 'rejected' && $status != 'aborted' && !in_array($previous_status, $this->statusreversearray[$status]) && !$secondaryStatus)) {
            $is_reveresed = 1;
        }

        if ($previous_status == 'cancellation in-process' && $status == 'disbursed' && $is_reveresed == 0) {
            $is_reveresed = 1;
        }
        if($status == "query resolved"){
            $pendingReviews = CaseReviewRequest::getPendingCount($application_id);
            if ($pendingReviews > 0) {
                $message = $pendingReviews === 1
                    ? '1 Case Review reply is still pending.'
                    : $pendingReviews . ' Case Review replies are still pending.';
                if ($insideCall) {
                    return ['status' => 'FAIL', 'message' => $message];
                }
                return \response(['status' => 'FAIL', 'message' => $message], 422);
            }
            $status = "disbursement checklist done";
        }

        $auth_user_id = $this->auto_approved_status ? 107 : $user_id;

        if (in_array(Input::get('source'), ['abfl_bre', 'jm_bre', 'vivriti_bre', 'utkarsh_bre'])){
            $statusLogsData = StatusLogs::where('application_id', $application_id)->where('status', 'cf approved')->first(['user_id']);
            if(isset($statusLogsData->user_id)){
                $auth_user_id = $statusLogsData->user_id;
            }
        }

        if (!$is_reveresed || $status == 'waiting for documents' || $status == 'disbursement checklist done') {
            // when nach registered is done manually
            if($status == 'nach registered' && $previous_status == 'disbursed'){
                $payload = [
                    'payload' => json_encode(array_merge(['id' => $application_id, 'status' => $status, 'previous_status' => $previous_status, 'auth_user_id' => $auth_user_id, 'lender_id' => (Input::has('lender_id') ? Input::get('lender_id') : 2)], Input::all())),
                    'from' => 'statusChange',
                    'application_id' => $application_id,
                    'available_at' => Carbon::now()->toDateTimeString(),
                    'created_at' => Carbon::now()->toDateTimeString(),
                    'is_available' => 1
                ];
                JobProvider::insert($payload);
            } else {
                $input = Input::all();
                if($insideCall){
                    $input['status'] = $status;
                    $input["previous_status"] = $previous_status;
                }
                $payload = [
                    'payload' => json_encode(array_merge(['is_reversed_status' => $is_reveresed, 'id' => $application_id, 'status' => $status, 'previous_status' => $previous_status, 'auth_user_id' => $auth_user_id, 'lender_id' => (Input::has('lender_id') ? Input::get('lender_id') : 2)], $input)),
                    'from' => 'statusChange',
                    'application_id' => $application_id,
                    'available_at' => Carbon::now()->toDateTimeString(),
                    'created_at' => Carbon::now()->toDateTimeString()
                ];
                JobProvider::insert($payload);
            }
        }

        $consumerUpdateLenderStatus = ['state' => $status];
        if (in_array(Input::get('source'), ['abfl_bre', 'jm_bre', 'vivriti_bre', 'utkarsh_bre'])){
            $consumerUpdateLenderStatus['lender_id'] = Input::get('lender_id');
        }

        ConsumerApplication::where('id', $application_id)->update($consumerUpdateLenderStatus);

        if ($status == 'in-process') {
            if ($application_status && ($application_status->created_by == null || $application_status->created_by < 0)) {
                ConsumerApplication::where('id', $application_id)
                    ->update(['created_by' => $user_id]);
            }
        }

        if ($status == "disbursed") {
            CollectionManger::assignCollectionAdvisor($application_id);
            $emi_count = ApplicationEMICalculation::where('application_id', $application_id)->first();
            if($emi_count->remaining_emi == 1){
                ConsumerApplicationElement::where('application_id', $application_id)->update(['repayment_type' => 2]);
                $disb_date = Carbon::now()->toDateTimeString();
                $disb_date_f = Carbon::parse($disb_date);
                $repay_date = Carbon::parse($emi_count->emi_date);
                $p_days = $disb_date_f->diffInDays($repay_date);
                $loanamount = ((isset($application_status->approved_amount) && $application_status->approved_amount != 0) ? $application_status->approved_amount : $application_status->loan_amount) - $emi_count->upfront_from_customer;
                $subvention_amount = (isset($emi_count->subvention) && $emi_count->subvention > 0) ? ((((isset($application_status->approved_amount) && $application_status->approved_amount != 0) ? $application_status->approved_amount : $application_status->loan_amount) * ($emi_count->subvention)) / 100) : 0;
                $amount_disbursed = $loanamount - $subvention_amount;
                $c = (1/$p_days);
                $d = $c;
                $v = $emi_count->emi/(-$amount_disbursed);
                $irr_data = (pow(-$v, $d) - 1);
                $irr_data_anuualize = $irr_data*365;
                $irr_data_percent = round($irr_data * 100, 2);
                $irr_data_anuualize_percent = round($irr_data_anuualize * 100, 2);
                ApplicationEMICalculation::where('application_id', $application_id)->update(["irr_rate"=>$irr_data_percent, "annualised_irr"=>$irr_data_anuualize_percent]);
                $this->sendslackmessage($application_id, $status);
        }
        }

        if ($status == "approved") {
            ConsumerApplicationElement::where('application_id', $application_id)->update(['agreement_version' => 2]);
            $this->sendslackmessage($application_id, $status);
            // $this->aadharMobileLinkCheckDcd($application_id);
        }



        $this->updateSystemReminders($application_id);

        $reason = '';
        if ($status == 'rejected') {
            $reason = Input::has('rejection_reason') ? Input::get('rejection_reason') : '';
        } else if ($status == 'approved') {
            $reason = Input::has('approved_reason_list') ? Input::get('approved_reason_list') : '';
        } else if ($status == 'aborted') {
            $reason = Input::has('abort_reason') ? Input::get('abort_reason') : '';
            if($reason!=''){
                $abort_reason = "Abort Reason: ".$reason.".";
                Comments::insert([
                    'application_id' => $application_id,
                    'user_id' => $user_id,
                    'comment' => $abort_reason,
                    'show_consumer' => 0,
                    'show_merchant' => 0,
                    'created_at' => Carbon::now()->toDateTimeString(),
                    'updated_at' => Carbon::now()->toDateTimeString(),
                    'type' =>'consumer',
                ]);
            }
        }

        StatusLogs::insert([
            'application_id' => $application_id,
            'user_id' => $auth_user_id,
            'status' => $status,
            'reason' => $reason,
            'is_reversed' => $is_reveresed,
            'created_at' => Carbon::now()->toDateTimeString()
        ]);

        if($this->auto_approved_status){
            $this->auto_approved_status = false;
        }

        if ($status == 'disbursement checklist done') {
            $item = isset($application_status->bank_details) && isset($application_status->bank_details->karza_response) ? json_decode($application_status->bank_details->karza_response) : [];
            $item = isset($item->result) ? $item->result : '';
            if (!isset($item->bankResponse) || (isset($item->bankResponse) && empty($item->bankResponse) && isset($item->bankTxnStatus) && $item->bankTxnStatus !== true)) {
                $application_link = asset("admin/consumer-applications/edit/" . $application_id);
                try {
                    $application_link = Shortio::getUrl($application_link);
                } catch (\Exception $e) {
                }
                $userLists = User::where('id', [598, 519, 6])->get(['mobile_number']);
                $mNumbers = [];
                foreach ($userLists as $list) {
                    $mNumbers[] = $list->mobile_number;
                }
                $reasonStatus = !isset($item->bankResponse) ? 'Failed to Validated Bank' : $item->bankResponse;
                array_push($mNumbers, $application_status->advisor->mobile_number);
                sendWhatsAppMessage(implode(',', $mNumbers), 'Bank Validation failed - Reason of failure is ' . $reasonStatus . ' - ' . $application_link);
            }

            // $this->aadharMobileLinkCheckDcd($application_id);

        }

        if (Input::has('approved_reason_list') || Input::has('rejection_reason')) {
            $comment = '';
            if (Input::has('approved_reason_list') && Input::get('approved_reason_list')) {
                $comment = 'Approved Reason: ' . Input::get('approved_reason_list');
            } else if (Input::has('rejection_reason') && Input::get('rejection_reason')) {
                $comment = 'Rejection Reason: ' . Input::get('rejection_reason');
            }
            if ($comment) {
                saveComment($comment, $application_id, $user_id);
            }
        }

        if(Auth::check() && in_array(Auth::user()->lender_id, [AvanseServices::$lender_id, Services::$lender_id]) && $status == 'rejected'){
            StatusLogs::insert([
                'application_id' => $application_id,
                'user_id' => $user_id ? $user_id : 107,
                'status' => 'cf approved',
                'reason' => '',
                'is_reversed' => 0,
                'created_at' => Carbon::now()->toDateTimeString()
            ]);
        }else if ($status == 'rejected'){
            $this->webhook($application_id, ['merchant_id' => $application_status->merchant_id, 'type' => 'Application-Webhook', 'status' => $status, 'data' => $this->getMConnectPayload($application_id, $status)]);
        }

        // Staging categories - 3, 7 (PL and Salary Advance)
        // Production categories - 3, 26, 44 (PL, Salary Advance, SME)
        $merchants = Merchant::where('status','inactive')->orWhere('is_guest_active', '!=', 1)->orWhereIn('category_id', [3, 26, 44])->get(['id']);

        if($status == 'closed' && $application_status['lender_id'] == AvanseServices::$lender_id){
            $noc_insert[] = [
                'application_id' => $application_id,
                'is_available' => 0,
                'execution_status'=>'pending',
                'created_at' => Carbon::now()->toDateTimeString()
            ];
            AvanseNoc::insert($noc_insert);
            event(new EventAvanseNoc());
        }

        $ids = [];
        foreach($merchants as $merchant){
            array_push($ids,$merchant->id);
        }

        if ($status == 'in-process' && in_array($application_status->updated_by,['admin','Partner Link','merchant admin panel', 'WhatsApp'])&& !in_array($application_status->merchant_id, $ids)) {

            $credit_report = CreditReport::where('application_id', $application_id)
                                        ->where('applicant_type', 1)
                                        ->whereNull('deleted_at')
                                        ->first();

            $credit_report_co_app = CreditReport::where('application_id', $application_id)
                                                ->where('applicant_type', 2)
                                                ->whereNull('deleted_at')
                                                ->first();

            $app_bureau_response = $co_app_bureau_response = ['status' => 'FAIL'];
            $is_approved = 0;

            if (!isset($credit_report->id)) {
                $app_bureau_response = $this->generateSoftBureauReport($application_id);
                $app_bureau_response = $app_bureau_response->getData();
                if (isset($app_bureau_response->is_approved) && $app_bureau_response->is_approved==1) {
                    $is_approved = 1;
                }
            }

            if (!isset($credit_report_co_app->id)) {
                $call_bre = $is_approved !== 1;
                $co_app_bureau_response = $this->generateSoftBureauReport($application_id,"customer",2,$call_bre);
                $co_app_bureau_response = $co_app_bureau_response->getData();
                if ($call_bre && isset($co_app_bureau_response->is_approved) && ($co_app_bureau_response->is_approved == 1)) {
                    $is_approved = $co_app_bureau_response->is_approved;
                }
            }

            $response_messages = [
                'OK' => "Applicant And CoApplicant Soft Bureau Pulled Successfully",
                'OK_APP' => "Applicant Soft Bureau Pulled Successfully",
                'OK_CO_APP' => "CoApplicant Soft Bureau Pulled Successfully",
                'FAIL' => "​Applicant name, co-applicant name, or mobile number is missing."
            ];

            $status = "FAIL";
            $message = $response_messages['FAIL'];
            if (!isset($credit_report_co_app->id) || !isset($credit_report->id)){
            if ((isset($app_bureau_response->status) && $app_bureau_response->status === "OK") && (isset($co_app_bureau_response->status) &&  $co_app_bureau_response->status === "OK")) {
                $status = "OK";
                $message = $response_messages['OK'];
            } elseif (isset($app_bureau_response->status) && $app_bureau_response->status === "OK") {
                $status = "OK";
                $message = $response_messages['OK_APP'];
            } elseif (isset($co_app_bureau_response->status) &&  $co_app_bureau_response->status === "OK") {
                $status = "OK";
                $message = $response_messages['OK_CO_APP'];
            }


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


        return response()->json(['status' => 'OK'], 200);}catch (\Exception $e) {
            $cwFactory->logger(json_encode(['application id' => $application_id, 'message' => $e->getMessage(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString()]));
            return \response()->json(['status' => 'FAIL']);

        }
    }

    public function aadharMobileLinkCheckDcd($applicant_id)
    {
        // Fetch mobile number and Aadhaar card for the given applicant
        $consumerApplication = ConsumerApplication::where('id', $applicant_id)->first(['mobile_number', 'aadhaar_card']);

        if (!$consumerApplication) {
            return;
        }

        $mobile_number = $consumerApplication->mobile_number;
        $aadhaar_card = $consumerApplication->aadhaar_card;

        $consumer_application_element = ConsumerApplicationElement::where('application_id', $applicant_id)->first(['id']);
        if (!$consumer_application_element) {
            return;
        }

        $applicationElement = ConsumerApplicationElement::find($consumer_application_element->id);

        if (!$applicationElement) {
            return;
        }

        // Check if both mobile number and Aadhaar card are available
        if (!empty($mobile_number) && !empty($aadhaar_card)) {
            $karzaApi = new KarzaApi();
            $linkedData = $karzaApi->checkAadhaarMobileLink($aadhaar_card, $mobile_number);

            $isMobileLinked = $linkedData['result']['isMobileLinked'] ?? null;
            $statusCode = $linkedData['statusCode'] ?? null;

            // Set linked status based on response
            if ($statusCode == 101) {
                if ($isMobileLinked === "Yes") {
                    $applicationElement->linked_status = 1;
                } elseif ($isMobileLinked === "No") {
                    $applicationElement->linked_status = 0;
                }
            } else {
                $applicationElement->linked_status = 0;
            }

        } else {
            // Reset linked status if mobile number or Aadhaar card is missing
            $applicationElement->linked_status = null;
        }

        // Save the updated status
        $applicationElement->save();
    }


    public function checkKWValidation($application_id)
    {
        $application_data = ConsumerApplication::with('application_element')->where('id', $application_id)->first(['id', 'purpose', 'approved_amount', 'loan_amount']);

        $application = (object)$application_data; // Assuming $application_data is an array or object

        if ($application->purpose == _env("SOLAR_CATEGORY_ID")) {

            $kw_value = isset($application->application_element->inverter_KW_installation) ? $application->application_element->inverter_KW_installation : 0;
            $loan_amount = isset($application->loan_amount) ? (float)$application->loan_amount : 0;

            // Query to retrieve max_approved_value based on KW value
            $max_approved_value = DB::table('kw_installation_records')
                                    ->where('KW', $kw_value)
                                    ->value('max_approved_value');

            // Compare loan_amount with max_approved_value
            if ($loan_amount > $max_approved_value) {
                return false; // Loan amount exceeds max approved value
            } else {
                return true; // Loan amount is within or equal to max approved value
            }
        } else {
            return true; // Loan amount is within or equal to max approved value
        }
    }

    public function webhook($application_id, $data){
        if(isset($data['merchant_id']) && $data['merchant_id']) {
            $id = $data['merchant_id'];
        }else{
            $consumerApplication = ConsumerApplication::where('id', $application_id)->first(['id','merchant_id']);
            $id = $consumerApplication->merchant_id ?? '';
        }
        $status = $data['status'];
        $webhooks = Webhook::where('merchant_id', $id)->orderby('created_at','desc')->get(['id','events']);
        $webhookIds = [];
        foreach ($webhooks as $webhook) {
            if (isset($webhook->id) && (in_array($data['status'], explode(',', $webhook->events)) || in_array($data['type'], explode(',', $webhook->events)))) {
                $webhookIds[] = $webhook->id;
            }
        }

        if($webhookIds){
            if (isset($data['pre_eligibility']) && $data['pre_eligibility']) {
                $payload = $data['data'];
                $payload['status'] = $data['status'];
            } else {
                $proFormaInvoice = ProFormaInvoice::where('application_id', $application_id)->first(['loan_application_no']);
                $agreementNo = $proFormaInvoice->loan_application_no ?? $this->getLoanAgreemenNumber($application_id);
                $payload = ['returnCode' => '000000', 'applicationNo' => strtoupper($agreementNo), 'type' => $data['type'], 'status' => $status, 'data' => $data['data'] ?? new \stdClass()];
                //if($id == 7305){ //TalentEdge uniqueIdNumber handled (Because they are using setu integration, to map at their end it requires)
                    $consumerApplicationElement = ConsumerApplicationElement::where('application_id', $application_id)->first(['unique_id_number']);
                    if(isset($consumerApplicationElement->unique_id_number)){
                        $payload['uniqueIdNumber'] = $consumerApplicationElement->unique_id_number;
                    }
                //}
            }
            event(new EventMConnectWebhook(['webhook_id' => json_encode($webhookIds), 'application_id' => $application_id, 'payload' => $payload]));
        }
    }

    public function vendorWebhook($application_id, $data){
        if(isset($data['vendor_id']) && $data['vendor_id']) {
            $id = $data['vendor_id'];
        }else{
            $consumerApplication = ConsumerApplicationElement::where('application_id', $application_id)->first(['id','vendor_id', 'product_name']);
            $id = $consumerApplication->vendor_id ?? 0;
        }
        if($id) {
            $hashids = new Hashids('Creditfair by CS', 20);
            $application_hashed_id = $hashids->encode($application_id);
            $status = $data['status'];
            $webhooks = \App\VendorWebhook::where('vendor_id', $id)->orderby('created_at', 'desc')->get(['id', 'events']);
            $webhookIds = [];
            foreach ($webhooks as $webhook) {
                $webhook_array = array('NACH-Webhook', 'RazorPay-Webhook', 'Paytm-Webhook', 'Cashfree-Webhook', 'Digio-VKYC-Webhook');
                if (isset($webhook->id) && (in_array($data['status'], explode(',', $webhook->events)) || (isset($data['type']) && in_array($data['type'], $webhook_array)))) {
                    $webhookIds[] = $webhook->id;
                }
            }

            if ($webhookIds) {
                $proFormaInvoice = ProFormaInvoice::where('application_id', $application_id)->first(['loan_application_no']);
                $agreementNo = $proFormaInvoice->loan_application_no ?? $this->getLoanAgreemenNumber($application_id);
                // event(new EventVendorWebhook(['webhook_id' => json_encode($webhookIds), 'application_id' => $application_id, 'payload' => ['returnCode' => '000000', 'hashed_application_id' => $application_hashed_id, 'applicationNo' => $agreementNo, 'type' => $data['type'], 'status' => $status, 'data' => $data['data'] ?? array()]]));
                return ['webhook_id' => json_encode($webhookIds), 'application_id' => $application_id, 'payload' => ['returnCode' => '000000', 'hashed_application_id' => $application_hashed_id, 'applicationNo' => strtoupper($agreementNo), 'type' => $data['type'], 'status' => $status, 'data' => $data['data'] ?? array()]];
            }
        }
        return null;
    }

    public function getMConnectPayload($id, $status, $additionalFields = array()){
        $payload = new \stdClass();
        $application = ConsumerApplication::with('proFormaInvoice', 'lender','merchant', 'emi', 'offer', 'application_element')->where('id', $id)->whereNull('is_deleted')->first();
        switch ($status){
            case 'approved':
                $consumerDocument = new ConsumerDocument(new Request());
                $data = $consumerDocument->getEsignLink($id);

                $emiCalculation = ApplicationEMICalculation::where('application_id', $id)->first(['processing_fee', 'emi', 'offer_id', 'interest_rate', 'tenure', 'payable_by_customer', 'upfront_from_customer']);
                if(isset($emiCalculation->offer_id)) {
                    $payload = ['esign' => $data['esign'],  'enach' => ($application->lender_id == 2 || $application->lender_id == \App\BlackSoil::$lender_id) ? $consumerDocument->getNachLink($id) : null, 'approved_amount' => $data['approved_amount'], 'offer_id' => $emiCalculation->offer_id, 'emi' => $emiCalculation->emi, 'tenure' => $emiCalculation->tenure, 'interest_rate' => $emiCalculation->interest_rate, 'processing_fee' => $emiCalculation->processing_fee, 'up_front_from_customer' => $emiCalculation->upfront_from_customer, 'total' => $emiCalculation->payable_by_customer];
                }
                $payload['bre_approved'] = false;
                if(isset($additionalFields['user_id']) && $additionalFields['user_id'] == 107) {
                    $payload['bre_approved'] = true;
                }
                break;
            case 'rejected':
                $payload = ['bre_approved' => false, 'message' => 'Application Rejected', 'application-status' => 'rejected'];
                if (isset($additionalFields['reason'])) {
                    $payload = ['reason' => $additionalFields['reason'], 'applicant_type' => $additionalFields['applicant_type']];
                    if (isset($additionalFields['signing'])) {
                        $payload['signing'] = $additionalFields['signing'];
                    }
                    if (isset($additionalFields['income'])) {
                        $payload['income'] = $additionalFields['income'];
                    }
                }
                break;
            case 'cf approved':
                if(isset($application->id)) {
                    $payload = ['approved_amount' => $application->approved_amount, 'tenure' => $application->emi->tenure ?? null];
                }
                $payload += ['bre_approved' => true, 'message' => 'Application Approved', 'application-status' => 'cf approved'];
                break;
            case 'waiting for decision':
                $payload = ['message' => 'Application Under Review', 'application-status' => 'waiting for decision'];
                $checkApproval = DB::select('select id from approval_status_log where application_id ='.$id.' and status = 1');
                if (isset($checkApproval[0]->id)) {
                    $payload['bre_approved'] = true;
                } else {
                    $link = _env('NO_TOUCH_URL').'/onboarding/bank-statement?merchant_sse='._env('SSE_MERCHANT_ID').'&application_id='.$id;
                    $payload['bre_approved'] = false;
                    $payload['bank_statement_link'] = $link;
                }
                break;
            case 'waiting for documents':
                $doc_list = $this->getPendingDocumentsList($id);
                $payload = ['docs' => isset($doc_list)? $doc_list: ''];
                $checkApproval = DB::select('select id from approval_status_log where application_id ='.$id.' and status = 1');
                if (isset($checkApproval[0]->id)) {
                    $payload['bre_approved'] = true;
                } else {
                    $link = _env('NO_TOUCH_URL').'/onboarding/bank-statement?merchant_sse='._env('SSE_MERCHANT_ID').'&application_id='.$id;
                    $payload['bre_approved'] = false;
                    $payload['bank_statement_link'] = $link;
                }
                $payload += ['message' => 'Application Pending Approval', 'application-status' => 'waiting for documents'];
                break;
            case 'ready for disbursement':
                $net_disbursement_amount = (new DisbursementController(new Request()))->getDisbursementAmount($application);
                $payload = ['disbursed_amount' => $net_disbursement_amount['net_disbursement'] ?? 0, 'approved_amount' => $application->approved_amount];
                $advancePaymentReceipt = DB::select('select id from consumer_application_files where consumer_application_id ='.$id.' and file_type="advance_amount_receipt" and deleted_at is null');
                $payload['advance_payment_receipt'] = $advancePaymentReceipt ? true : false;
                break;
            case 'disbursed':
                $net_disbursement_amount = (new DisbursementController(new Request()))->getDisbursementAmount($application);
                $payload = ['disbursed_amount' => $net_disbursement_amount['net_disbursement'] ?? 0, 'approved_amount' => $application->approved_amount];
                break;
            case 'utr':
                $net_disbursement_amount = (new DisbursementController(new Request()))->getDisbursementAmount($application);
                $payload = ['disbursed_amount' => $net_disbursement_amount['net_disbursement'] ?? 0, 'approved_amount' => $application->approved_amount, 'utr' => $additionalFields['utr']];
                break;
            case 'Merchant-Comment':
                $payload = ['merchant_comment' => $additionalFields['comment']];
                break;
            case 'Add-Co-applicant':
                $payload = ['message' => 'Add CoApplicant', 'reason' => $additionalFields['reason'], 'comment' => ''];
                break;
            case 'DA-Confirmation-Webhook':
                // Load only specific columns
                $application = ConsumerApplication::with([
                    'emi' => function($query) {
                        $query->select('emi', 'tenure', 'interest_rate', 'remaining_emi', 'application_id');
                    },
                    'merchant' => function($query) {
                        $query->select('id', 'merchant_name', 'gst_number');
                    },
                    'application_element.merchant_center' => function($query) {
                        $query->select('name');
                    }
                ])->where('id', $id)->first(['id', 'merchant_id', 'mobile_number', 'co_applicant_mobile_number', 'name', 'co_applicant_name', 'created_at', 'current_address_line_1', 'current_address_state', 'current_address_city', 'current_address_pincode', 'approved_amount']);
                $typeOfCustomerMap = [1 => 'Residential', 2 => 'Bharat MSME', 3 => 'Urban C&I (MSME)', 4 => 'Housing Society', 5 => 'DSA'];
                $typeOfCustomer = $typeOfCustomerMap[$application->application_element->type_of_customer ?? null] ?? '';
                $payload = ["merchantGstNumber" =>  wall_decrypt($application->merchant->gst_number ?? ''),
                    "merchantCenter" => $application->application_element->merchant_center->name ?? '',
                    "invoiceDate" => Carbon::parse($application->created_at)->toDateTimeString(),
                    "applicantName" => $application->name,
                    "coApplicantName" => $application->co_applicant_name ?? '',
                    "coApplicantMobileNumber" => $application->co_applicant_mobile_number ? wall_decrypt($application->co_applicant_mobile_number) : '',
                    "applicantAddress" => $application->current_address_line_1 . ', ' . $application->current_address_city . ', ' . $application->current_address_state . ', ' . $application->current_address_pincode,
                    "mobileNumber" => wall_decrypt($application->mobile_number),
                    "tenure" => $application->emi->tenure,
                    "remainingTenure" => $application->emi->remaining_emi,
                    "interestRate" => $application->emi->interest_rate,
                    "installmentAmount" => $application->emi->emi,
                    "loanSanctionedAmount"=> $application->approved_amount,
                    "projectSize" => $application->application_element->inverter_KW_installation ?? '',
                    "typeOfCustomer" => $typeOfCustomer];
                break;
            case 'document-verified':
                $payload = ['doc_type' => $additionalFields['doc_type'] ?? '', 'doc_status' => $additionalFields['doc_status'] ?? '', 'reason' => $additionalFields['reason'] ?? ''];
                break;
            case 'table-of-offers-webhook':
                $link = _env('NO_TOUCH_URL').'/onboarding/bank-statement?merchant_sse='._env('SSE_MERCHANT_ID').'&application_id='.$id;
                $offers = $this->getTableOfOffersMConnectPayload($id);
                $payload = [
                    'message' => empty($offers) ? 'No applicable offer' : 'Table of offers webhook',
                    'bank_statement_link' => $link,
                    'offers' => $offers,
                ];
                break;
            default:
                break;
        }
        return $payload;
    }

    public function getTableOfOffersMConnectPayload($applicationId)
    {
        $application = ConsumerApplication::where('id', $applicationId)->first(['loan_amount']);
        $appLoanAmount = $application->loan_amount ?? 0;

        $payloadOffers = collect();

        $approvedAmounts = LoanDecisionApprovedAmount::where('application_id', $applicationId)
            ->whereNull('deleted_at')
            ->get(['offer_id', 'policy_type', 'emi_amount', 'calculated_approved_amount']);

        $validApprovedAmounts = $approvedAmounts->filter(function($row) use ($appLoanAmount) {
            return $row->calculated_approved_amount >= 50000 && $row->calculated_approved_amount <= $appLoanAmount;
        });

        if ($validApprovedAmounts->isNotEmpty()) {
            $offerDetails = $this->getMerchantOfferDetailsForTableOfOffers($validApprovedAmounts->pluck('offer_id')->all());

            $approvedPayload = $validApprovedAmounts->map(function ($approvedAmount) use ($offerDetails) {
                return $this->formatTableOfOffersPayloadRow(
                    $approvedAmount->offer_id,
                    $approvedAmount->calculated_approved_amount,
                    $approvedAmount->emi_amount,
                    $approvedAmount->policy_type,
                    $offerDetails
                );
            });
            $payloadOffers = $payloadOffers->merge($approvedPayload);
        }

        $decisionRows = DecisionTable::where('application_id', $applicationId)
            ->whereNull('deleted_at')
            ->get();

        if ($decisionRows->isNotEmpty()) {
            $offerDetails = $this->getMerchantOfferDetailsForTableOfOffers($decisionRows->pluck('offer_id')->all());

            // A decision row with status 0 is a minimum_tenure offer, any other status is a
            // residual_emi offer. Both use the eligible_amount / emi of the row, while the
            // bureau surrogate offer uses its own amount / emi columns.
            foreach ($decisionRows as $row) {
                if ($row->status == 0 && $row->eligible_amount >= 50000 && $row->eligible_amount <= $appLoanAmount) {
                    $payloadOffers->push($this->formatTableOfOffersPayloadRow(
                        $row->offer_id,
                        $row->eligible_amount,
                        $row->emi,
                        'minimum_tenure',
                        $offerDetails
                    ));
                }

                if ($row->status != 0 && $row->eligible_amount >= 50000 && $row->eligible_amount <= $appLoanAmount) {
                    $payloadOffers->push($this->formatTableOfOffersPayloadRow(
                        $row->offer_id,
                        $row->eligible_amount,
                        $row->emi,
                        'residual_emi',
                        $offerDetails
                    ));
                }

                if ($row->bureau_surrogate_limit_amount >= 50000 && $row->bureau_surrogate_limit_amount <= $appLoanAmount) {
                    $payloadOffers->push($this->formatTableOfOffersPayloadRow(
                        $row->offer_id,
                        $row->bureau_surrogate_limit_amount,
                        $row->bureau_surrogate_limit_emi,
                        'bureau_surrogate_limit',
                        $offerDetails
                    ));
                }
            }
        }

        return $payloadOffers->unique('offer_id')->values()->all();
    }

    private function getMerchantOfferDetailsForTableOfOffers($offerIds)
    {
        $offerIds = array_values(array_unique(array_filter($offerIds)));

        if (empty($offerIds)) {
            return collect();
        }

        return MerchantOffers::whereIn('id', $offerIds)
            ->get(['id', 'interest_rate', 'tenure', 'processing_fee'])
            ->keyBy('id');
    }

    private function formatTableOfOffersPayloadRow($offerId, $loanAmount, $emi, $offerType, $offerDetails)
    {
        $offer = $offerDetails->get($offerId);
        
        $finalOfferId = $offerId;
        if ($offerType === 'bureau_surrogate_limit') {
            $finalOfferId = $offerId . '_b';
        } elseif ($offerType === 'residual_emi') {
            $finalOfferId = $offerId . '_r';
        } elseif ($offerType === 'BANKING-ABB') {
            $finalOfferId = $offerId . '_a';
        } elseif ($offerType === 'POWER-SAVING') {
            $finalOfferId = $offerId . '_p';
        }

        return [
            'offer_id' => $finalOfferId,
            'eligible_amount' => $loanAmount,
            'emi' => $emi,
            'roi' => $offer->interest_rate ?? null,
            'tenure' => $offer->tenure ?? null,
            'processing_fee' => $offer->processing_fee ?? null,
        ];
    }

    public function getPendingDocumentsList($id){
        $consumer_applications = ConsumerApplication::with('application_element')->where('id', $id)->first(['id']);
        $application_data_array = [];
        if ($consumer_applications->application_element && $consumer_applications->application_element->mandatory_document_list) {
            $documents = explode(',', $consumer_applications->application_element->mandatory_document_list);
            foreach ($documents as $document) {
                $application_data_array[] = $this->getDocumentMappingMConnect($document);
            }
        }

        return array_values(array_filter($application_data_array)) ?? array();
    }

    public function getAALink($id){
        $application = ConsumerApplicationElement::where('application_id', $id)->first(['id','mandatory_document_list']);
        $fKey = '3_month_bank_statement';
        if(isset($application->mandatory_document_list) && in_array($fKey, explode(',', $application->mandatory_document_list))) {
            $data = $this->getAccountAggregatorLink(new Request(['id' => $id]));
            $account_aggregator = $data->getData();
            if (isset($account_aggregator->status) && $account_aggregator->status == 'OK') {
                return $account_aggregator->link ?? false;
            }
        }

        return false;
    }

    public function getDocumentMappingMConnect($doc){
        $docs = ['PAN' => ['pan_card'],
            'APPLICANT_AADHAAR_FRONT' => ['aadhar_card'],
            'SECURITY_CHEQUE' => ['PDC'],
            'ELECTRICITY_BILL' => ['electricity_bill'],
            'GAS_BILL' => ['gas_bill'],
            'PASSPORT' => ['passport'],
            'BANK_STATEMENT' => ['3_month_bank_statement', '6_month_bank_statement'],
            'SALARY_SLIP' => ['none'],
            'ITR' => ['itr'],
            'MCA' => ['none'],
            'UTILITY_BILL_VALIDATION' => ['Utility Bill'],
            'CPV' => ['cpv'],
            'ENACH' => ['emandate'],
            'RENT_AGREEMENT' => ['rent_agreement'],
            'SALE_DEED' => ['sale_deed'],
            'SHOP_ACT' => ['none'],
            'GST_CERTIFICATE' => ['none'],
            'CO_APPLICANT_BANK_STATEMENT_3' => ['none'],
            'CO_APPLICANT_PAN' => ['none'],
            'CO_APPLICANT_AADHAAR_FRONT' => ['none'],
            'CO_APPLICANT_AADHAAR_BACK' => ['none'],
            'CO_APPLICANT_PHOTO' => ['none'],
            'CO_APPLICANT_ITR' => ['co_applicant_itr'],
            'CO_APPLICANT_GST' => ['co_applicant_gst'],
            'PASSBOOK' => ['passport'],
            'OTH' => ['none']];
        foreach($docs as $docNameKey => $docName){
            if (in_array($doc, $docName)){
                return $docNameKey;
            }
        }
        return $doc;
    }

    public function updateStatusFromJob($application_id)
    {

        $application_status = ConsumerApplication::with('emi','category', 'application_element', 'application_additional', 'merchant', 'bank_details', 'disbursementOfferDisbursed', 'activeOffer')
                ->where('id', $application_id)
                ->first([
                    'id', 'lender_id','user_id','merchant_id','state', 'name', 'mobile_number',
                    'email', 'approved_amount', 'loan_amount','pan_card','aadhaar_card','co_applicant_pan_card',
                    'co_applicant_aadhaar_card','merchant_id','co_applicant_mobile_number','co_applicant_name',
                    'co_applicant_email','applicant_id','offer_id','purpose', 'updated_by', 'created_by', 'secondary_status']);
        $old_status = (isset($application_status->state)) ? $application_status->state : "";
        $mode = (isset($application_status->updated_by)) ? $application_status->updated_by : "";


        $previous_status = (Input::has('state') && Input::get('previous_state')) ? Input::get('previous_state') : (Input::has('previous_status') ? Input::get('previous_status') : $this->current_status);

        $status = (Input::has('status') && Input::get('status')) ? Input::get('status') : (Input::has('state') ? Input::get('state') : $this->current_status);
        if ($status == 'rejected'){
            $addn_data = ['user_id' => Input::get('auth_user_id'), 'reason' =>Input::get('reason')];
        }else{
            $addn_data = ['user_id' => Input::get('auth_user_id')];
        }
        try{
            $this->webhook($application_id, ['merchant_id' => $application_status->merchant_id, 'type' => 'Application-Webhook', 'status' => $status, 'data' => $this->getMConnectPayload($application_id, $status, $addn_data, $application_status->merchant_id)]);
            $payloadDataVendor = (new ConsumerApplicationController())->vendorWebhook($application_id, ['type' => 'Application-Webhook','status' => $status, 'data' => $this->getMConnectPayload($application_id, $status)]);
            if ($payloadDataVendor) {
                $vendorWebhook = new VendorWebhook();
                $vendorWebhook->handle('Application-Webhook', $payloadDataVendor);
            }
            //For NTC Cases
            $s = Input::get('auth_user_id');
            if($status == 'waiting for decision' && Input::has('auth_user_id') && Input::get('auth_user_id') != 107) {
                $creditReportData = CreditReport::where('application_id', $application_id)->whereBetween('Score', [-1, 10])->first(['id']);
                if(isset($creditReportData->id)) {
                    $statusNTC = 'ntc';
                    $this->webhook($application_id, ['merchant_id' => $application_status->merchant_id, 'type' => 'Decision-Webhook', 'status' => $statusNTC, 'data' => $this->getMConnectPayload($application_id, $statusNTC)]);
                }
            }
            if(isset($application_status->created_by) && $application_status->created_by) {
                sendFCMNotification([
                    'type' => 'admin_user',
                    'id' => $application_status->created_by,
                    'notification_type' => 'status-update',
                    'device_id' => 'admin-user',
                    'title' => 'Application Update',
                    'body' => 'Hi, Your application ' . $application_status->name . ' is in' . $status . "Reason: ". $application_status->reason,
                    'deeplink' => asset("admin/consumer-applications/edit/" . $application_id)
                ]);
            }
        }catch (\Exception $e){
            (new Slack(new Request(['title' => 'Mconnect Webhook job creation failed', 'fields' => ['e' => $e->getMessage(),'l' => $e->getLine(),'t' => $e->getTraceAsString(), 'id' => $application_id], 'group' => Slack::$STAGE_TESTING])))->send();
        }

        if (($mode != 'EMI CHECKOUT' && strtolower($old_status) == strtolower($status) || $mode == 'EMI CHECKOUT') && ($status == 'rejected' || $status == 'aborted' || in_array($previous_status, $this->statusreversearray[$status]))) {
//            $this->webhook($application_id, ['merchant_id' => $application_status->merchant_id, 'type' => 'Application-Webhook', 'status' => $status, 'data' => $this->getMConnectPayload($application_id, $status)]);

            if (_env('WHATSAPP_STATUS_AND_COMMENT')){
                try {
                    $groupNotificationStatuses = [
                        'incomplete form', 'form completed', 'in-process', 'waiting for documents',
                        'waiting for decision', 'pre approved', 'cf approved', 'approved', 'rejected'
                    ];
                    if (in_array(strtolower($status), $groupNotificationStatuses)) {
                        (new ServiceController(new Request()))->sendGroupStatusNotification($application_id, $status);
                    }
                } catch (\Exception $e) {
                    (new Slack(new Request(['title' => 'Whatsapp notification sending on status change failed', 'fields' => ['e' => $e->getMessage(),'l' => $e->getLine(),'t' => $e->getTraceAsString(), 'id' => $application_id], 'group' => Slack::$STAGE_TESTING])))->send();
                }
            }   

            if ($status == 'rejected') {
                (new ConsumerApplicationController())->applicationReject($application_id);
                $this->insertIntoJob($application_id, 'referral_communication', $status);
            }
            /*ConsumerApplication::where('id',$application_id)
                ->update(['state'=>$status]);*/

            if ($status == 'rejected' || $status == 'aborted' && ($application_status->merchant_id != _env("Finsall_id"))) {
                $this->sendMessageToMerchant($status, $application_id, Input::has('auth_user_id'));
            }

            $blackListData = $this->getBlacklistData($application_status);
            if ($status == 'in-process') {
                if($blackListData['status'] == true) {
                    (new Slack(new Request(['title' => 'Blacklisted by RBI', 'fields' => ['Customer Name' => $application_status->name, 'application_id' => $application_status->id, 'flag' => $blackListData['flag']]])))->send();
                }

                $this->updateProforma($application_id);
                $this->updateAdvisor($application_id);
                $this->checkApprovedPinCode($application_id);
                if($application_status->merchant_id != 6543) {
                    if($application_status->merchant_id != _env("Finsall_id")){
                    $this->sendInProcessWhatsAppMessage($application_id);}
                    $this->startEscalation($application_id, $status);
                }
            }

            if ($status == 'cancelled' && ($application_status->merchant_id != _env("Finsall_id"))) {
                $this->sendClosureLetter($application_id);
            }

            if ($old_status != "cancelled") {
                if ($status == "waiting for decision" || $status == "disbursement checklist done" || $status == "approved" || $status == "disbursed") {
                    $this->sendslackmessage($application_id, $status);
                    if($status == 'disbursement checklist done' && isset($application_status->merchant_id) && $application_status->application_element->type_of_customer != 2){ // Atta chakki cases excluded as per the request on fresh desk 6313 from Neha and Himanshu (BD)
                        $emiCalculation = new \App\Http\Controllers\Admin\EMICalculation(new Request());
                        $reviseDocumentNeeded = $emiCalculation->updateEMIDate($application_id, $application_status->activeOffer->subvention_type_id, $application_status->merchant_id);
                        if ($reviseDocumentNeeded) {
                            $payload = [
                                "cam" => "1", "proforma" => "1", "sanction" => 1, "loanagreement"=> 1, "emi_schedule"=>1, "payment_links"=> 0
                            ];
                            $request = new Request();
                            $request->merge([
                                'id' => $application_id,
                                'data' => $payload
                            ]);
                            $this->reviseDocuments($request);
                        }
                        $merchatData = Merchant::where('id',$application_status->merchant_id)->first(['send_da_on_checklist']);
                        if(isset($merchatData->send_da_on_checklist) && $merchatData->send_da_on_checklist){
                            $this->sendProForma($application_id, false, true);
                        }
                        if ($application_status->lender_id == AvanseServices::$lender_id ) { // && $application_status->approved_amount <= 300000
                            $this->reviseDocumentOnEmiChange($application_status,$application_id);
                        }
                        if($application_status->activeOffer->subvention_type_id == 1 && $application_status->lender_id != AvanseServices::$lender_id){
                            $this->reviseDocumentOnEmiChange($application_status,$application_id);
                        }
                    }
                }

                if($status == 'disbursed' || $status == 'nach registered'){
                    $this->updateAppDataInfo(new Request(['application_id' => $application_id, 'user_id' => $application_status->user_id, 'status' => 'disbursed']));
                }

                if($status == 'nach registered'){
                    $request = new Request();
                    $request->request->add([
                        'type' => 'Pro Forma Invoice',
                        'test_bot' => false,
                        'bot' => true
                    ]);
                    $document = (new ConsumerDocument($request));
                    $consumerDocument = $document->getDocument($application_id);
                    // (new Slack(new Request(['title' => 'Multistage error logs20', 'fields' => ['application_id' => $application_id]])))->send();
                    if(isset($consumerDocument['user']['phase_cycle']) && $consumerDocument['user']['phase_cycle'] > 1){
                        $this->invokeCommunication($application_id);
                        $applicationElement = ConsumerApplicationElement::where('application_id', $application_id)->where('is_payout', 1)->first(['id']);
                        if(isset($applicationElement->id)){
                            $this->disbursementThrough = true;
                        }
                        // (new Slack(new Request(['title' => 'Multistage error logs23', 'fields' => ['application_id' => $application_id]])))->send();
                        $this->disburseViaMultiStage($application_id, $consumerDocument);
                    }
                }

                if ($status == 'disbursed') {
                    JobProvider::where('application_id', $application_id)->where('from', 'karzaPurge')->update(['is_available' => 0]);
                    (new LoanManagement())->paymentCalculate($application_id);
                    $this->generateInvoice($application_id);
                    $this->updatePreviousNach($application_id);
                    $this->processingFeeNotification($application_id);

                    if(isset($application_status->lender_id) && !in_array($application_status->lender_id, [Singularity::$lender_id, Vivriti::$lender_id, Capri::$lender_id])) {
                        $consumerDocument = $this->sendWelcomeLetter($application_id);
                    }else{
                        $request = new Request();
                        $request->request->add([
                            'type' => 'Welcome Letter',
                            'test_bot' => false,
                            'bot' => true
                        ]);
                        $consumerDocument = (new ConsumerDocument($request))->getDocument($application_id);
                    }
                    $this->invokeCommunication($application_id);
                    $this->updatestatustonachregister($application_id);
                    $this->updateProcessFeesPayment($application_id);
                    $this->updateLegalChargesPayment($application_id);
                    $this->updateInsuranceFeesPayment($application_id);
                    $applicationElement = ConsumerApplicationElement::where('application_id', $application_id)->where('is_payout', 1)->first(['id']);
                    if(isset($applicationElement->id)){
                        $this->disbursementThrough = true;
                    }
                    // (new Slack(new Request(['title' => 'Multistage error logs-1', 'fields' => ['application_id' => $application_id]])))->send();
                    $this->disburseViaMultiStage($application_id, $consumerDocument);
                    $this->whatsAppCommunication($application_status);
                    $this->initiateAAMonitoringRequest($application_id, 'disbursal');
                }elseif($status == 'ready for disbursement'){
                    if ($application_status->lender_id == AvanseServices::$lender_id) {
                        $this->setDisbursementStatusJobs($application_status);
                    }
                    if ($application_status->lender_id == AvanseServices::$lender_id ) { // && $application_status->approved_amount <= 300000
                        $this->reviseDocumentOnEmiChange($application_status,$application_id);
                    }
                    if($application_status->activeOffer->subvention_type_id == 1 && $application_status->lender_id != AvanseServices::$lender_id){
                        $this->reviseDocumentOnEmiChange($application_status,$application_id);
                    }
                    if($application_status->activeOffer->subvention_type_id > 1 && $application_status->lender_id != AvanseServices::$lender_id){
                        $this->generateRPSforBPI($application_status,$application_id);
                    }
                    //Call onefin APIs
                    //$this->pushToOnefin(new Request(['id' => $application_id]));
                } elseif ($status == 'cf approved') {
                    // if(!$application_status->merchant->table_of_offers){
                    $this->sendSoftApprovalCommunication($application_status);
                    // }
                    if(Input::has('auth_user_id') && Input::get('auth_user_id') == 107){
                        $this->sendAutoSoftApprovalCommunication($application_status);
                    }
                    if($application_status->lender_id == Services::$lender_id){
                        return false;
                    }
                    if(in_array($application_status->merchant_id, LendBox::activatedMerchants()) && (!Input::has('lender_id') || (Input::has('lender_id') && Input::get('lender_id') == LendBox::$lender_id))) {
                        ConsumerApplication::where('id', $application_id)->update(['lender_id' => LendBox::$lender_id]);
                        //if ($application_status->lender_id === ConsumerApplication::AVANSE_LENDER_ID) {
                    }
                    else if(in_array($application_status->merchant_id, LendBoxLSP::activatedMerchants()) && (!Input::has('lender_id') || (Input::has('lender_id') && Input::get('lender_id') == LendBoxLSP::$lender_id))) {
                        ConsumerApplication::where('id', $application_id)->update(['lender_id' => LendBoxLSP::$lender_id]);
                    }
                    else if(in_array($application_status->merchant_id, AvanseProcesses::activatedMerchants()) && (!Input::has('lender_id') || (Input::has('lender_id') && Input::get('lender_id') == AvanseServices::$lender_id))) {
                        ConsumerApplication::where('id', $application_id)->update(['lender_id' => AvanseServices::$lender_id]);
                        event(new EventPostCreateCustomer($application_status->id));
                        $this->sendCFApprovedCommunication($application_status);

                        // New Loan Application
                        event(new EventPostCreateFinance($application_status->id));
                        //$this->rabbitMQQueue();
                    }else if(in_array($application_status->merchant_id, KMGP2P::activatedMerchants()) && (!Input::has('lender_id') || (Input::has('lender_id') && Input::get('lender_id') == KMGP2P::$lender_id))) {
                        ConsumerApplication::where('id', $application_id)->update(['lender_id' => KMGP2P::$lender_id]);
                    }
                    //}
                } elseif ($status == 'approved') {
                    if ($application_status->lender_id == AvanseServices::$lender_id ) { // && $application_status->approved_amount > 300000

                        /* Re-generate documents if avanse changed the approved amount*/
                        $this->regenerateDocuments($application_id);

                        /*
                            on application approval if application is tagged to avanse,
                            then only send the VKYC notifications
                            post VKYC if KYC results to approval then sanction letter
                            and other formalities will be done
                         */

                        /*$return = $this->requestHypervergeKYC($application_id, 'arr');

                        if(!empty($return['status']) && $return['status'] === 'OK') {
                            if(!empty($return['customer_link'])) {
                                $reqObj = new Request(['customer_link' => $return['customer_link'], 'applicant_type' => 1]);
                                $out = $this->sendHypervergeKYC($reqObj, $application_id);
                            }
                            if(!empty($return['co_customer_link'])) {
                                $reqObj = new Request(['co_customer_link' => $return['co_customer_link'], 'applicant_type' => 2]);
                                $out = $this->sendHypervergeKYC($reqObj, $application_id);
                            }
                        }*/
                        /*
                            below code is added for safety purpose to generate the ananse payment links in advance.
                            As it is taking time to generate, code halted because of the same
                            First applicant and co-applicant do the hyperverge KYC. If kYC approved then sanction letter email would be sent immediately without any problem as payment links has already been generated
                        */
                        $request = new Request();
                        $request->request->add([
                            'type' => 'Sanction Letter',
                            'bot' => true,
                            'from_mail' => _env('CENTRALOPS')
                        ]);

                        $document = (new ConsumerDocument($request));
                        $document->getDocument($application_id);
                    } else {
                        event(new EventTableOfOffer(['id' => $application_id]));
                        $this->saveLiabilityPercent($application_status, $application_id, 'job');
                        $this->checkApprovedPinCode($application_id);
                        $this->ApprovalInit($application_status, $application_id);
                        $this->disbursementOffers($application_id);
                        (new Slack(new Request(['title' => 'Before Sanction Letter func', 'fields' => ['application_id' => $application_id ?? '']])))->send();
                        $isError = $this->sendSanctionLetter($application_id);
                        (new Slack(new Request(['title' => 'After Sanction Letter func', 'fields' => ['application_id' => $application_id ?? '', 'Err' => json_encode($isError)]])))->send();
                        $this->sendProForma($application_id);
                        (new Slack(new Request(['title' => 'After DA func', 'fields' => ['application_id' => $application_id ?? '']])))->send();

                        if($application_status->merchant_id != 6543){
                            $this->initiateForLatestBankStatement($application_id);
                            $this->sendemandate($application_id);
                            $this->proformaSigningNotification($application_id);
                            $this->creditLimitNotification($application_id);
                            $this->insertIntoJob($application_id, 'referral_communication', $status);
                            $this->whatsAppCommunication($application_status, $status);
                        }

                        $this->checkMobileWithAadhar($application_id, $application_status);

                        if ($application_status->merchant_id == _env("Finsall_id")) {
                            $move_new_status_to = "disbursement checklist done";
                            // $documentTypes = ['customer_photo', 'aadhar_xml', 'pan_card']; // Document types to check for

                            $documentTypes = ['other', 'aadhar_card', 'customer_photo', 'aadhar_xml', 'pan_card']; // Document types to check for
                            $existingDocumentTypes = ConsumerApplicationFiles::where('consumer_application_id', $application_id)->whereNull('deleted_at')->whereIn('file_type', $documentTypes)->distinct()->pluck('file_type')->toArray();
                            if (count($existingDocumentTypes) === count($documentTypes)){
                                $this->updateApplicationStatus($application_id, $move_new_status_to, true);
                                (new Slack(new Request(['title' => 'Updated Application to Disbursement Checklist Done', 'fields' => ['application_id' => $application_id ?? '','merchant'=> 'Finsall']])))->send();
                            }else{
                                (new Slack(new Request(['title' => 'Error updating status', 'fields' => ['application_id' => $application_id ?? '','error'=> 'Document Check Failed']])))->send();
                            }
                        }

                        if (isset($isError) && ($isError instanceof RedirectResponse || $isError instanceof Redirect)) {
                            if ($error = $isError->getSession()->get('error')) {
                                (new Slack(new Request(['title' => 'Update from job error', 'fields' => ['application_id' => $application_id ?? '','error'=> $error ?? '']])))->send();
                                $cwFactory = new CloudWatchLoggerFactory();
                                $data = array('title' => 'Update from job error', 'application_id' => $application_id ?? '','error'=> $error ?? '');
                                $cwFactory->logger(json_encode($data));
                                return response()->json(['status' => 'FAIL', 'message' => $error], 200);
                            }
                        }
                    }
                } elseif ($status == 'waiting for documents') {
                    if($application_status->merchant_id != 6543 && (!Input::has('is_reversed_status') || !Input::get('is_reversed_status'))) {
                        $this->sendAccountAggregatorLink($application_id, $application_status->mobile_number);
                        $this->waitingForDocumentNotification($application_id);
                        $this->startEscalation($application_id, $status);
                    }
                } elseif ($status == 'waiting for decision') {
                    $this->checkMobileWithAadhar($application_id, $application_status);
                    if($application_status->merchant_id != 6543) {
                        $this->startEscalation($application_id, $status);
                    }
                    $this->autoFetchGST($application_id, $application_status->pan_card, $application_status->co_applicant_pan_card);
                } else if ($status == 'closed') {

                    $this->sendWithHoldCommunication($application_id);
                    // Closure letter to be not sent for settlement cases
                    if (empty($application_status->secondary_status) && !in_array($application_status->secondary_status, ['settlement-in-progress', 'settlement-done', 'settled'])) {
                        $this->sendClosureLetter($application_id);
                    } else {
                        $this->sendSettlementLetter($application_id, false);
                    }

                    if(Input::get('cancel_nach')){
                        $this->cancelNachs($application_id);
                    }
                }
                else if ($status == 'pre approved') {
                    $this->checkApprovedPinCode($application_id);
                    if($application_status->merchant_id != 6543) {
                        $this->sendPreApprovalCommunication($application_id);
                        if(Input::has('auth_user_id') && Input::get('auth_user_id') == 107){
                            $this->sendAutoPreApprovalCommunication($application_id);
                        }
                    }
                }
            }
            $this->rollbackJobChanges(['application_id' => $application_id], $status);
        }
        return response()->json(['status' => 'OK'], 200);
    }


    public function autoFetchGST($application_id,$pan_card, $co_applicant_pan_card) {
        $application_status = ConsumerApplication::with(['application_element'])
            ->where('id', $application_id)
            ->first(['id', 'pan_card', 'co_applicant_pan_card', 'employee_status', 'purpose', 'co_applicant_employee_status']);

        if (!$application_status) return;

        if ($this->isValidForGST($application_status, 1)) {
            $this->processGSTPan($application_id, $application_status->pan_card, 1);
        }

        if ($this->isValidForGST($application_status, 2)) {
            $this->processGSTPan($application_id, $application_status->co_applicant_pan_card, 2);
        }
    }

    private function isValidForGST($app, $type) {
        $appElement = $app->application_element;

        $isSolarPurpose = ($app->purpose == _env('SOLAR_CATEGORY_ID'));
        $validCustomerType = $appElement && in_array($appElement->type_of_customer, [1, 3]);
        $validUserType = $appElement && in_array(strtoupper($appElement->type_of_customer_application), ['INDIVIDUAL', 'NON-INDIVIDUAL']);

        if (!$isSolarPurpose || !$validCustomerType || !$validUserType) {
            return false;
        }

        if ($type === 1) {
            $hasPan = !empty($app->pan_card);
            $validEmpStatus = in_array($app->employee_status, [
                'Self Employed - Professional',
                'Self Employed - Business',
                'BUSINESS'
            ]);
            return $hasPan && $validEmpStatus;
        }

        if ($type === 2) {
            $hasPan = !empty($app->co_applicant_pan_card);
            $validEmpStatus = ($app->co_applicant_employee_status === 'BUSINESS');
            return $hasPan && $validEmpStatus;
        }

        return false;
    }

    private function processGSTPan($application_id, $pan, $type){
        if (!$pan) {
            return;
        }

        $exists = GSTPANData::where('application_id', $application_id)
            ->where('type', $type)
            ->whereNull('deleted_at')
            ->exists();

        try {
            $cwFactory = new CloudWatchLoggerFactory();
            $logData = [
                'application_id' => $application_id,
                'user_id'        => 107,
                'vendor'         => 'Karza_GST_Check',
                'type'           => $type,
                'pan'            => $pan,
                'status'         => $exists ? 'Blocked - Duplicate found' : 'Proceeding - No duplicate found',
                'gst_entry_exists'       => $exists,
                'timestamp'      => microtime(true) 
            ];
            $cwFactory->logger(json_encode($logData));
        } catch (\Exception $e) {
        }

        if ($exists) {
            return;
        }

        $request = new Request([
            'application_id' => $application_id,
            'user_id'        => 107,
            'type'           => $type,
            'pan'            => $pan,
        ]);

        $this->getGSTPanDetails($request);
    }

    public function sendAccountAggregatorLink($application_id, $mobile_number){
        $application = ConsumerApplicationElement::where('application_id', $application_id)->first(['id','mandatory_document_list']);
        $fKey = '3_month_bank_statement';
        if(isset($application->mandatory_document_list) && in_array($fKey, explode(',', $application->mandatory_document_list))) {
            $accountAggregator = new AccountAggregator(new Request(['id' => $application_id, 'mobile_number' => $mobile_number]));
            $accountAggregator->initiate();
        }
    }

    public function calculateFirstEMIDate($application, $isAvanse = false, $offer_details = null)
    {
        $day = date('j'); // Gets the day of the month as a number (1-31)
        
        $subvention_type_id = $application->activeOffer->subvention_type_id ?? ($offer_details->subvention_type_id ?? 1);

        if ($subvention_type_id > 1 && $day != 5) {
            $startDate = strtotime(date('Y-m-d', strtotime('now + 31 days')));
            $endDate = strtotime(date('Y-m-d', strtotime('now + 64 days')));
        } elseif ($subvention_type_id > 1 && $day == 5) {
            $startDate = strtotime(date('Y-m-d', strtotime('now + 22 days')));
            $endDate = strtotime(date('Y-m-d', strtotime('now + 45 days')));
        } else {
            // SSE merchant subvention/0 DP cases first emi date move to next to next month after 15th
            if ($day <= 20) {
                $startDate = strtotime(date('Y-m-d', strtotime('now + 15 days')));
                $endDate = strtotime(date('Y-m-d', strtotime('now + 45 days')));
                if ($application->merchant_id == _env('SSE_MERCHANT_ID') && $day >= 16) {
                    $startDate = strtotime(date('Y-m-d', strtotime('now + 20 days')));
                    $endDate = strtotime(date('Y-m-d', strtotime('now + 50 days')));
                }
            } else {
                $startDate = strtotime(date('Y-m-d', strtotime('now + 30 days')));
                $endDate = strtotime(date('Y-m-d', strtotime('now + 60 days')));
            }
            if (isset($application->application_element) && $application->application_element->is_bnpl) {
                $startDate = strtotime(date('Y-m-d', strtotime('now + 60 days')));
                $endDate = strtotime(date('Y-m-d', strtotime('now + 90 days')));
            }
        }

        $i = 0;
        $arrayDate = $subvention_type_id > 1 ? [5] : [5]; // 18 emi date removed as per request freshdesk 6329

        if ($isAvanse) {
            $arrayDate = [7];
            if(Carbon::now()->day <= 20){
                $timestamp = new Carbon('first day of next month');
                $startDate = $timestamp->timestamp;
                $endDate = Carbon::parse(date('Y-m-d', $startDate))->addDays(45)->timestamp;
            }else{
                $timestamp = new Carbon('first day of next month');
                $startDate = $timestamp->addMonth(1)->timestamp;
                $endDate = Carbon::parse(date('Y-m-d', $startDate))->addDays(45)->timestamp;
            }
        }

        // For Igris Merchant - AD-hoc Business requirement
        if(isset($application->merchant_id) && $application->merchant_id == 6875){
            $startDate = strtotime(date('Y-m-d', strtotime('now + 75 days')));
            $endDate = Carbon::parse(date('Y-m-d', $startDate))->addDays(45)->timestamp;
        }

        if(isset($application->merchant_id) && $application->merchant_id == 6990){
            $startDate = strtotime(date('Y-m-d', strtotime('now + 75 days')));
            $endDate = Carbon::parse(date('Y-m-d', $startDate))->addDays(45)->timestamp;
        }

        $available_dates = array();
        do {
            $newTime = strtotime('+' . $i++ . ' days', $startDate);
            if (in_array(date('d', $newTime), $arrayDate)) {
                array_push($available_dates, date('Y-m-d', $newTime));
            }
        } while ($newTime < $endDate);

        return $available_dates[0];
    }

    public function generateRPSforBPI($application, $final_offer_id = 0){
        $offer_details = MerchantOffers::where('id', $application->offer_id)->first(['id','interest_type_id', 'subvention_type_id']);

        $available_date = $this->calculateFirstEMIDate($application, false, $offer_details);
        $emi_date = date('Y-m-d H:i:s', strtotime($available_date));

        $first_emi_date = $emi_date ?? $application->emi->emi_date;
        $request = (new Request());
        $request->request->add([
            // changing date format here for generateemi function
            'first_emi_date' => $first_emi_date,
            'loan_amount' => $application->approved_amount,
            'merchant_id' => $application->merchant_id,
            'category_id' => $application->category->id,
            'interest_type_id' => $offer_details->interest_type_id,
            'merchant_offer_id' => $application->offer_id,
        ]);
        $this->generateEMI($request, $application, $application->id);
    }

    /* Changing emi date and documents for post 20th date when status is changed to 'ready for disbursement' or 'disbursement checklist done' */
    public function reviseDocumentOnEmiChange($appData,$id){
        if(Carbon::now()->toDateString() >= Carbon::now()->firstOfMonth()->addDays(20)->toDateString()){
            $this_month = Carbon::now()->firstOfMonth()->addDays(20);
            $emi_month = Carbon::parse($appData->emi->emi_date);
            $diff = $this_month->diffInMonths($emi_month,false);
            if($diff < 1){
                $request = new Request();
                $offer = MerchantOffers::where('id', $appData->offer_id)->first(['interest_type_id']);
                if($diff < 0){
                    $newEmiDate = Carbon::parse($appData->emi->emi_date)->addMonths(abs($diff)+2)->format('d/m/Y');
                }else{
                    $newEmiDate = Carbon::parse($appData->emi->emi_date)->addMonth()->format('d/m/Y');
                }
                $request->request->add([
                        // changing date format here for generateemi function
                        'first_emi_date' => $newEmiDate,
                        'loan_amount' => $appData->approved_amount,
                        'merchant_id' => $appData->merchant_id,
                        'category_id' => $appData->category->id,
                        'interest_type_id' => $offer->interest_type_id,
                        'merchant_offer_id' => $appData->offer_id,
                    ]);
                $this->generateEMI($request, $appData, $id);
                $this->sendProForma($id);
                /* removing previous loan agreement esign documents */
                ConsumerApplicationFiles::where('consumer_application_id',$id)->where('file_type','loan_agreement_esign')->where('created_by','!=', 107)->delete();
                (new FrontController())->sendEsignToCustomer($id, true);
                $isError = $this->sendSanctionLetter($id);
                if ($isError instanceof RedirectResponse || $isError instanceof Redirect) {
                    if ($error = $isError->getSession()->get('error')) {
                        return response()->json(['status' => 'FAIL', 'message' => $error], 200);
                    }
                }
            }
        }
    }

    public function setDisbursementStatusJobs($application){
        $payload[] = [
            'payload' => json_encode(['id' => $application->id, 'applicant_id' => $application->applicant_id, 'applicant_type' => 1]),
            'from' => 'initiateUTRStatusAvanse',
            'application_id' => $application->id,
            'available_at' => Carbon::now()->addHour(2)->toDateTimeString(),
            'created_at' => Carbon::now()->toDateTimeString()
        ];

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

    public function cancelNachs($application_id){

        $mandates = Mandate::where('consumer_application_id', $application_id)->where('status','active')->get();

        foreach ($mandates as $mandate){
            if($mandate->umrn) {
                $data = $mandate->toArray();
                $data['status'] = 'cancelled';
                (new MandateLogs())->lockPrevious($mandate, $mandate->id, new Request($data));

                Mandate::where('id', $mandate->id)->update(['status' => 'cancelled','created_at' => Carbon::now()->toDateTimeString()]);
            }
        }

        /*$request = new Request([
            'nachs' => $ids
        ]);*/
        //(new NachController($request))->cancelMandate($request);
    }

    public function initiateForLatestBankStatementToSlack($id){
        $application = ConsumerApplication::where('id', $id)->where('state','approved')->whereNull('is_deleted')->first(['id','name','created_by','user_id','state']);
        $advisor_id = isset($application->user_id) && isset($application->user_id) ? $application->user_id : '';
        $slack_url = isset($consumer->advisor) && isset($consumer->advisor->slack_url) ? $consumer->advisor->slack_url : '';
        if(isset($application->id)){
            try {
                    $segment = User::where('id', $advisor_id)->first(['id', 'name', 'slack_id','slack_url']);
                        if(isset($segment->slack_id) && $segment->slack_id) {
                            (new Slack(new Request(['title' => 'Please upload latest bank statement - ' . $application->name,
                            'fields' => ['name' => $application->name, 'id' => $id, 'status' => $application->state], 'group' => "loan_application",'tagging'=>[$advisor_id]])))->send();

                            (new Slack(new Request(['title' => 'Please upload latest bank statement - ' . $application->name,
                            'fields' => ['name' => $application->name, 'id' => $id, 'status' => $application->state], 'group' => $segment->slack_url])))->send();
                        }

                $emails[] = 'centralops@creditfair.in';
                if ($application->created_by) {
                    $user = User::find($application->created_by);
                    if (isset($user->email) && $user->email) {
                        $emails[] = $user->email;
                    }
                }

                Mail::send('emails.reminders.basic_reminder',
                    ['body' => 'Please upload latest bank statement. Please ' . '<a href="https://creditfair.in/admin/consumer-applications/edit/' . $id . '">click here</a> to upload the bank statement.']
                    , function ($message) use ($application, $emails) {
                        $message->to($emails)->subject('Please upload latest bank statement - ' . $application->name);
                    });
            }catch (\Exception $e){

            }
        }
    }

    public function initiateForLatestBankStatement($id, $today = false){


        $_job = JobProvider::where('application_id', $id)->where('from','initiateForLatestBankStatement')->where('is_available', 0)->first(['id']);

        if(isset($_job->id)){
            if($today){
                JobProvider::where('id', $_job->id)->update(['available_at' => Carbon::now()->addDays(30)->toDateTimeString()]);
            }
            return false;
        }

        $date = '';

        if($today) {
            $application = ConsumerApplication::where('id', $id)->where('state', 'approved')->first(['id']);

            if (!isset($application->id)) {
                return false;
            }
        }

        if(!$today) {
            $file = ConsumerApplicationFiles::where('consumer_application_id', $id)->where('file_type', 'bank_statement')->orderBy('created_at','desc')->first(['id', 'created_at']);
            if(isset($file->created_at)) {
                $date = explode(' ', $file->created_at)[0];
            }else{
                return false;
            }
        }else{
            $date = Carbon::now()->toDateString();
        }

        if($date) {

            $payload[] = [
                'payload' => json_encode(['id' => $id]),
                'from' => 'initiateForLatestBankStatement',
                'application_id' => $id,
                'available_at' => Carbon::createFromFormat('Y-m-d', $date)->addDay(30)->toDateTimeString(),
                'created_at' => Carbon::now()->toDateTimeString()
            ];

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

    public function saveLiabilityPercent($application_status, $application_id, $type = null){
        $multiStageDisbursement = new MultiStageDisbursement();
        if (!$multiStageDisbursement->canPartialDisbursement($application_status->offer_id, $application_status)) {
            if(!$type) {
                $proforma = ProFormaInvoice::with('fldg_category')->where('application_id', $application_id)->first();

                if(isset($proforma->fldg_category->id) && $proforma->liability_hold == 1) {
                    $liability_amount = \App\Http\Controllers\Admin\LiabilityController::calculateLiabilityHoldAmount($application_status->approved_amount, $application_status->emi->upfront_from_customer,$proforma->fldg_category->fldg, $proforma);

                    $isExistLiabilityLog = LiabilityLog::where('application_id', $application_id)->where('liability_percent', $proforma->fldg_category->fldg)->first(['id']);
                    if (!isset($isExistLiabilityLog->id)) {
                        $liability_log = new LiabilityLog();
                        $liability_log->application_id = $application_id;
                        $liability_log->liability_percent = $proforma->fldg_category->fldg;
                        $liability_log->liability_amount = $liability_amount;
                        $liability_log->created_at = Carbon::now()->toDateTimeString();
                        $liability_log->save();

                        LiabilityLog::where('application_id', $application_id)->where('id', '!=', $liability_log->id)->delete();
                    } else {
                        LiabilityLog::where('id', $isExistLiabilityLog->id)->update(['liability_amount' => $liability_amount]);
                    }
                    return true;
                }else{
                    LiabilityLog::where('application_id', $application_id)->whereNull('deleted_at')->delete();
                    return true;
                }
            }
        }
    }

    public function sendWithHoldCommunication($application_id){
        $application = ConsumerApplicationElement::with('application','application.merchant')->where('application_id', $application_id)->where('hold_amount','>',0)->where('withhold_adjusted','>',0)->first();
        if($application && $application->hold_amount && $application->withhold_adjusted){

            $body = "Dear Team,<br/>This is a reminder of the ".$application->application->name." case to refund the loss guarantee amount ".$application->hold_amount." to ".$application->application->merchant->merchant_name;

            $managerLists = StatusLogs::with('user')->where('application_id', $application_id)->get();

            $emails = [];
            foreach ($managerLists as $manager) {
                if ($manager->user && $manager->user->email && $application->application->created_by != $manager->user->id && $manager->user->user_type >= 5 && !in_array($manager->user->email, $emails)) {
                    array_push($emails, $manager->user->email);
                }
            }

            (new Slack(new Request(['title' => 'Loss Guarantee Amount Refund - '.$application->application->merchant->merchant_name,
                    'fields' => ['message' => $body, 'id' => $application_id],  'group' => 'payment_collection'])))->send();

            if($emails) {
                \Mail::send('emails.reminders.basic_reminder', [
                    'body' => $body,
                ], function ($message) use ($application, $emails) {
                    $message->to($emails)->subject('Loss Guarantee Amount Refund - ' . $application->application->merchant->merchant_name);
                    $message->cc('finance@creditfair.in');
                });
            }
        }
    }

    public function updatePreviousNach($application_id)
    {
        $ConsumerApplication = ConsumerApplication::with('emi')->where('id', $application_id)->first();
        $previous_mandate_id = (new NachService(new Request()))->isCustomerHasPreviousActiveNach($ConsumerApplication->applicant_id);
        if ($previous_mandate_id && $ConsumerApplication->emi) {
            $preMandate = Mandate::where('id', $previous_mandate_id)->first();
            $nachSetup = [
                'mandate_id' => $preMandate->mandate_id,
                'umrn' => $preMandate->umrn,
                'action' => $preMandate->action,
                'collection' => $preMandate->collection,
                'frequency' => $preMandate->frequency,
                'monthly_frequency' => $preMandate->monthly_frequency,
                'mandate_amount' => $ConsumerApplication->emi->emi,
                'status' => $preMandate->status,
                'mode' => $preMandate->mode,
                'mandate_url' => $preMandate->mandate_url,
                'applicant_id' => $preMandate->applicant_id,
                'expiry_date' => $preMandate->expiry_date,
                'until_cancelled' => $preMandate->until_cancelled,
                'consumer_application_id' => $application_id,
                'created_at' => Carbon::now()->toDateTimeString()
            ];
            Mandate::insert($nachSetup);
        }
    }

    public function isMultiLender($id){
        $numLender = MerchantWhitelistLender::where('merchant_id', $id)->whereNull('deleted_at')->count();
        $cwFactory = new CloudWatchLoggerFactory();
        $data = array('title' => 'Multi Lender Check', 'application_id' => $id ?? '', 'Number of lenders' => $numLender);
        $cwFactory->logger(json_encode($data));
        return $numLender;
    }

    public function ApprovalInit($application, $id, $byPass = false)
    {
        if(!$application){
            $application = ConsumerApplication::with('merchant')->where('id', $id)->first(['id','merchant_id','approved_amount','loan_amount','name']);
        }
        //Check merchant status
            $merchant = Merchant::where('id', $application->merchant_id)->where('pre_status', 1)->where('status','active')->first(['id','merchant_name']);
            if(isset($merchant->id)){
                (new Slack(new Request(['title' => 'One case of '.$merchant->merchant_name.' is approved. Please change the status from “Login and Training” to “Active for Disbursement”.', 'fields' => ['Name' => $application->name, 'ID' => $id], 'group' => 'businessdevelopment'])))->send();
            }
        //end

        //set fldg category - for auto approved cases
        $this->setFLDGCategoryAutoApprovedCases($application, $id, $byPass);
        //end


        if ($application && !$application->approved_amount && $application->loan_amount > 0) {
            ConsumerApplication::where('id', $id)->update(['approved_amount' => $application->loan_amount]);
        }

        $this->generateCAMReport($id);
    }

    public function setFLDGCategoryAutoApprovedCases($application, $id, $byPass){
        if(!$byPass) {
            $status = StatusLogs::where('status', 'approved')->where('user_id', 107)->first(['id']);
        }
        if(isset($status->id) || $byPass) {
            $proFormaInvoice = ProFormaInvoice::where('application_id', $id)->first(['id','fldg_applied', 'fldg_applied_category']);
            if(isset($proFormaInvoice->id) && !$proFormaInvoice->fldg_applied && !$proFormaInvoice->fldg_applied_category) {
                $merchant = Merchant::where('id', $application->merchant->id)->whereNotNull('auto_approve_category')->first(['id', 'auto_approve_category']);
                if (isset($merchant->id) && $merchant->auto_approve_category) {
                    $FLDGCategory = FLDGCategory::where('id', $merchant->auto_approve_category)->whereNull('deleted_at')->first(['id']);
                    if (isset($FLDGCategory->id)) {
                        ProFormaInvoice::where('application_id', $id)->update(['fldg_applied' => 1, 'fldg_applied_category' => $merchant->auto_approve_category]);
                    }
                }
            }
        }
    }

    public function disbursementOffers($application_id)
    {
        $disbursement = new MultiStageDisbursement();
        $disbursement->generateDisbursementOffers($application_id);
    }

    public function getPartialDisbursementData(Request $requestData, MultiStageDisbursement $disbursement)
    {
        $request = new Request();
        $request->request->add([
            'type' => 'Pro Forma Invoice',
            'bot' => true,
            'getPartialData' => true
        ]);
        $document = (new ConsumerDocument($request));
        $documentDetails = $document->getDocument($requestData->get('id'));

        $previousDisbursement = $disbursement->getPreviousDisbursement($requestData->get('id'));

        $data['merchant_name'] = $documentDetails['user']['merchant_name'];
        $data['disbursed_date'] = $documentDetails['user']['disbursed_date1'];

        $disbursementData = [];
        $previousDisbursementOffers = [];

        foreach ($previousDisbursement as $item) {
            if($item->phase > 1){
                $statusName = 'Disbursement Phase'.$item->phase;
                $status = StatusLogs::where('application_id',$requestData->get('id'))->where('status',$statusName)->orderBy('id','desc')->first(['created_at']);
                $data['disbursed_date'] = Carbon::parse($status->created_at)->toDateString();
            }else{
                $data['disbursed_date'] = Carbon::parse($data['disbursed_date'] ?? Carbon::now()->toDateString())->addDays($item->day_from_disbursement_date)->toDateString();
            }
            $previousDisbursementOffers[] = $item->disbursement_offer_id;
            $disbursementData[] = array('disbursement_amount' => round($item->disbursement_amount, 2), 'day_from_disbursement_date' => $item->day_from_disbursement_date, 'partial_subvention_amount' => $item->partial_subvention_amount, 'per_disbursement_amount' => $item->per_disbursement_amount, 'date' => $data['disbursed_date'],'phase'=>$item->phase, 'status' => 'Disbursed');
        }

        $next = $disbursement->getDisbursementProperties($requestData->get('id'), $documentDetails);

        // if(count($previousDisbursementOffers)){
        //     // compare if phase is already disbursed
        //     foreach($previousDisbursementOffers as $disbursedPhase){
        //         if($disbursedPhase != $next['disbursement_offer_id']){
        //             $disbursementData[] = array('disbursement_amount' => round($next['disbursement_amount'], 2), 'day_from_disbursement_date' => $next['day_from_disbursement_date'], 'partial_subvention_amount' => $next['partial_subvention_amount'], 'per_disbursement_amount' => $next['per_disbursement_amount'], 'date' => Carbon::parse($data['disbursed_date'])->addDays($next['day_from_disbursement_date'])->toDateString(), 'status' => 'Next');
        //             $previousDisbursementOffers[] = $next['disbursement_offer_id'];
        //         }
        //     }
        // }else{
            $disbursementData[] = array('disbursement_amount' => round($next['disbursement_amount'], 2), 'day_from_disbursement_date' => $next['day_from_disbursement_date'], 'partial_subvention_amount' => $next['partial_subvention_amount'], 'per_disbursement_amount' => $next['per_disbursement_amount'], 'date' => Carbon::parse($data['disbursed_date'])->addDays($next['day_from_disbursement_date'])->toDateString(), 'status' => 'Next');
            $previousDisbursementOffers[] = $next['disbursement_offer_id'];
        // }

        $pendings = $disbursement->getPendingDisbursementProperties($requestData->get('id'), $previousDisbursementOffers);

        foreach ($pendings as $pending) {
            $disbursementData[] = array('disbursement_amount' => round($pending['disbursement_amount'], 2), 'day_from_disbursement_date' => $pending['day_from_disbursement_date'], 'partial_subvention_amount' => $pending['subvention'], 'per_disbursement_amount' => $pending['per_disbursement_amount'], 'date' => Carbon::parse($data['disbursed_date'])->addDays($pending['day_from_disbursement_date'])->toDateString(), 'status' => 'Pending');
        }

        $data['partial_disbursement'] = $disbursementData;

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

    public function getPartialDisbursementData_v2(Request $requestData, MultiStageDisbursement $disbursement, $application)
    {
        $request = new Request();
        $request->request->add([
            'type' => 'Pro Forma Invoice',
            'bot' => true,
            'getPartialData' => true
        ]);
        $document = (new ConsumerDocument($request));
        $documentDetails = $document->getDocument($requestData->get('id'));
        $disbursementOffers = new DisbursementOffers();
        $disbursementOffersData = DisbursementOffers::where('application_id', $requestData->get('id'))->whereNull('deleted_at')->get();


        if ($disbursementOffersData){
            $disbursement = new MultiStageDisbursement();
            foreach ($disbursementOffersData as $index => $offer){
                $Disbursements[] = $disbursement->getPartialDisbursementAmount($application, ($offer->phase));
            }
        }
        foreach ($Disbursements as $index => $data) {
            $disbursementData[] = array('disbursement_amount' => round($data['disbursement_amount'], 2), 'day_from_disbursement_date' => $data['day_from_disbursement_date'], 'partial_subvention_amount' => $data['subvention'], 'gst_on_subvention' => $data['gst_on_subvention'], 'partial_subvention_amount_with_gst' => $data['subvention_with_gst'],'per_disbursement_amount' => $data['per_disbursement_amount'], 'status' => 'Pending');
        }
        $data['partial_disbursement'] = $disbursementData;

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


    public function updateProcessFeesPayment($id)
    {
        $application = ConsumerApplication::with('merchant', 'proFormaInvoice', 'emi')->where('id', $id)->first();
        if ($application && $application->emi && $application->emi->processing_fee > 0) {
            if(isset($application->proFormaInvoice->processing_fee_by_merchant)){
                if($application->proFormaInvoice->processing_fee_by_merchant == 0){
                    $proforma_pf = 0;
                }else if($application->proFormaInvoice->processing_fee_by_merchant == 1){
                    $proforma_pf = 1;
                }
            }

            $is_collected_by_merchant = $proforma_pf ?? ((isset($application->merchant->is_collected) && $application->merchant->is_collected == 1) ? $application->merchant->is_collected : 0);
            $cf_transaction_id = $application->id . strtoupper(substr($application->name, 0, 2)) . time();

            $paymentTransaction = PaymentTransaction::on('mysql_primary')->where('application_id', $id)->where('payment_for', 'processing_fee')->where('mode', 'Adjusted In disbursement')->whereNull('deleted_at')->first(['id']);

            if ($is_collected_by_merchant == 1 && !isset($paymentTransaction->id)) {
                $payment_transaction = new PaymentTransaction();
                $payment_transaction->emi_payment_id = 0;
                $payment_transaction->amount = $application->emi->processing_fee;
                $payment_transaction->mode = 'Adjusted In disbursement';
                $payment_transaction->paid_by = '';
                $payment_transaction->payment_reconciliation_date = date('Y-m-d');
                $payment_transaction->umrn = '';
                $payment_transaction->collected_by = 'Merchant';
                $payment_transaction->wallet_name = '';
                $payment_transaction->reason = '';
                $payment_transaction->trasanction_id = '';
                $payment_transaction->trasanction_acknowledgement = '';
                $payment_transaction->application_id = $id;
                $payment_transaction->payment_for = 'processing_fee';
                $payment_transaction->payment_date = date('Y-m-d');
                $payment_transaction->cf_transaction_id = $cf_transaction_id;
                $payment_transaction->bank_id = 1;
                $payment_transaction->status = 'success';
                $payment_transaction->save();
            }
        }

    }

    public function updateLegalChargesPayment($id)
    {
        $legal_charges_initial_date = "2025-01-13"; // Default date value set according to the stamp duty release
        $approvedLog = StatusLogs::where('application_id', $id)->where('status', 'approved')->orderBy('created_at', 'asc')->first(['created_at']);
        $legalChargesReleaseDate = Carbon::parse($legal_charges_initial_date);
        if ($approvedLog) {
            $approvedDate = Carbon::parse($approvedLog->created_at);
            if ($legalChargesReleaseDate->gt($approvedDate)) {
                return false;
            }
        }

        $application = ConsumerApplication::with('merchant', 'proFormaInvoice', 'emi')->where('id', $id)->first();
        if ($application && $application->emi && $application->emi->legal_charges > 0) {
            if(isset($application->proFormaInvoice->processing_fee_by_merchant)){
                if($application->proFormaInvoice->processing_fee_by_merchant == 0){
                    $proforma_pf = 0;
                }else if($application->proFormaInvoice->processing_fee_by_merchant == 1){
                    $proforma_pf = 1;
                }
            }

            $is_collected_by_merchant = $proforma_pf ?? ((isset($application->merchant->is_collected) && $application->merchant->is_collected == 1) ? $application->merchant->is_collected : 0);
            $cf_transaction_id = $application->id . strtoupper(substr($application->name, 0, 2)) . time();

            $paymentTransaction = PaymentTransaction::on('mysql_primary')->where('application_id', $id)->where('payment_for', 'legal_charges')->whereNull('deleted_at')->first(['id']);

            if ($is_collected_by_merchant == 1 && !isset($paymentTransaction->id)) {
                $payment_transaction = new PaymentTransaction();
                $payment_transaction->emi_payment_id = 0;
                $payment_transaction->amount = $application->emi->legal_charges;
                $payment_transaction->mode = 'Adjusted In disbursement';
                $payment_transaction->paid_by = '';
                $payment_transaction->payment_reconciliation_date = date('Y-m-d');
                $payment_transaction->umrn = '';
                $payment_transaction->collected_by = 'Merchant';
                $payment_transaction->wallet_name = '';
                $payment_transaction->reason = '';
                $payment_transaction->trasanction_id = '';
                $payment_transaction->trasanction_acknowledgement = '';
                $payment_transaction->application_id = $id;
                $payment_transaction->payment_for = 'legal_charges';
                $payment_transaction->payment_date = date('Y-m-d');
                $payment_transaction->cf_transaction_id = $cf_transaction_id;
                $payment_transaction->bank_id = 1;
                $payment_transaction->status = 'success';
                $payment_transaction->save();
            }
        }

    }

    public function updateInsuranceFeesPayment($id){
        $application = ConsumerApplication::with('proFormaInvoice')->where('id', $id)->first();
        $proFormaInvoice = $application->proFormaInvoice;
        if ((isset($proFormaInvoice->insurance_premium_applicable) && $proFormaInvoice->insurance_premium_applicable == 1 && $proFormaInvoice->insurance_premium_by_merchant == 1 && $proFormaInvoice->insurance_premium_amount > 0)) {
            $cf_transaction_id = $application->id . strtoupper(substr($application->name, 0, 2)) . time();


            $paymentTransaction = PaymentTransaction::on('mysql_primary')->where('application_id', $id)->where('payment_for', 'insurance_fee')->whereNull('deleted_at')->first(['id']);

            if (!isset($paymentTransaction->id)) {
                $payment_transaction = new PaymentTransaction();
                $payment_transaction->emi_payment_id = 0;
                $payment_transaction->amount = $proFormaInvoice->insurance_premium_amount;
                $payment_transaction->mode = 'Adjusted In disbursement';
                $payment_transaction->paid_by = '';
                $payment_transaction->payment_reconciliation_date = date('Y-m-d');
                $payment_transaction->umrn = '';
                $payment_transaction->collected_by = 'Merchant';
                $payment_transaction->wallet_name = '';
                $payment_transaction->reason = '';
                $payment_transaction->trasanction_id = '';
                $payment_transaction->trasanction_acknowledgement = '';
                $payment_transaction->application_id = $id;
                $payment_transaction->payment_for = 'insurance_fee';
                $payment_transaction->payment_date = date('Y-m-d');
                $payment_transaction->cf_transaction_id = $cf_transaction_id;
                $payment_transaction->bank_id = 1;
                $payment_transaction->status = 'success';
                $payment_transaction->save();
            }
        }
    }

    public function sendPreApprovalCommunication($application_id, $documentRuleID = 0)
    {

        setlocale(LC_MONETARY, 'en_IN.UTF-8');
        $application = ConsumerApplication::with('merchant', 'application_element', 'documents')->where('id', $application_id)->first();


        $schedules = $this->getEscalationRules($application->loan_amount, true);
        $days = 0;
        $date = date('d M, Y', Carbon::now()->timestamp);


        if ($schedules) {
            $schedules = array_values(array_filter($schedules));
            $days = isset($schedules[0]) ? $schedules[0] : 0;
            $date = date('d M, Y', Carbon::now()->addDay($days)->timestamp);
        }

        $documentRuleID = $documentRuleID ? $documentRuleID : ($application->application_element ? $application->application_element->auto_document_rule_id : 0);
        if ($documentRuleID) {
            $_docLists = (new GradeController(new Request(['isNumberedList' => true])))->getPreDocumentsList($documentRuleID, $application);
            $_docLists = $_docLists['_docLists'];
        } else {
            if (strtolower($application->employee_status) == 'salaried') {
                $_docLists = ['PAN card', 'Aadhar card or address proof', 'Utility bill', 'Latest Three months salary slips', 'Six months bank statement'];
            } else {
                $_docLists = ['PAN card', 'Aadhar card or address proof', 'Utility bill', 'Business proof', 'Two year Income Tax Return', 'Six months bank statement'];
            }


            $files = [];
            if ($application->documents) {
                foreach ($application->documents as $document) {
                    $docKey = strtolower(str_replace(' ', '_', $document->file_type));
                    if ($docKey == 'salary_slip') {
                        $files[] = 'pay_slip';
                    }
                    $files[] = $docKey;
                }
            }

            $receivedDocument = (new GradeController(new Request()))->isDocumentReceived($_docLists, $files);
            $_docLists = $lists = array_values($receivedDocument['lists']);


        }

        if ($_docLists) {
            $consumerApplicationElement = ConsumerApplicationElement::where('application_id', $application_id)->first(['id', 'mandatory_document_list']);
            if (isset($consumerApplicationElement->mandatory_document_list) && $consumerApplicationElement->mandatory_document_list) {
                $listDoc = $consumerApplicationElement->mandatory_document_list;
                $listDoc .= ',' . implode(',', array_values(array_map(function ($item) {
                        return strtolower(str_replace('/', ' or ', str_replace(' ', '_', isset(explode(') ', $item)[1]) ? explode(') ', $item)[1] : $item)));
                    }, $_docLists)));
            } else {
                $listDoc = implode(',', array_values(array_map(function ($item) {
                    return strtolower(str_replace('/', ' or ', str_replace(' ', '_', isset(explode(') ', $item)[1]) ? explode(') ', $item)[1] : $item)));
                }, $_docLists)));
            }
            if ($listDoc) {
                if (isset($consumerApplicationElement->id)) {
                    ConsumerApplicationElement::where('application_id', $application_id)->update(['mandatory_document_list' => $listDoc]);
                    if(Auth::check()) {
                        MandatoryDocumentListLogs::insert([
                            'application_id' => $application_id,
                            'user_id' => Auth::user()->id,
                            'mandatory_document_list' => $listDoc,
                            'created_at' => Carbon::now()->toDateTimeString()
                        ]);
                    }
                } else {
                    $consumerApplicationElement = new ConsumerApplicationElement();
                    $consumerApplicationElement->application_id = $application_id;
                    $consumerApplicationElement->mandatory_document_list = $listDoc;
                    $consumerApplicationElement->created_at = Carbon::now()->toDateTimeString();
                    $consumerApplicationElement->save();
                    if(Auth::check()) {
                        MandatoryDocumentListLogs::insert([
                            'application_id' => $application_id,
                            'user_id' => Auth::user()->id,
                            'mandatory_document_list' => $listDoc,
                            'created_at' => Carbon::now()->toDateTimeString()
                        ]);
                    }
                }
            }
        }

        $listString = '';
        $_listString = '';
        if ($_docLists) {
            $listString = '<ul style="list-style: none;">';
            foreach ($_docLists as $index => $list) {
                $listString .= '<li>' . ($index + 1) . ') ' . $list . '</li>';
                $_listString .= ($index + 1) . ')' . $list . "<br/>";
            }
            if(isset($index)) {
                $listString .= '<li>' . ($index + 1) . ') <a href="https://creditfair.in/netbanking/authentication/' . $application_id . '">Authenticate With NetBanking</a></li><li style="font-size: 10px;">(We don’t get access to your login password / Your data is secured by bank grade security)</li>';
            }
            $listString .= '</ul>';
        }

        if ($application->email && $application->merchant_id!= _env("Finsall_id")) {

            $subject = "🎉 You are Pre-Approved for your purchase from " . $application->merchant->merchant_name . '!';

            if(true){
                //(new ConsumerApplicationController())->sendPreApprovalCommunicationV1($application, $listString, $subject, new Request());
            }else{
                if ($listString) {
                    $customerEmail = 'Dear ' . $application->name . ',<br/>Congrats! You are pre-approved up to Rs ' . str_replace('.00', '', money_format('%!i', $application->loan_amount)) . ' subject to submission of following documents:<br/><br/>' . $listString . '<br/><br/>Please note that the final loan amount and offer might differ.*The pre-approval will expire on ' . $date . '.*';

                } else {
                    $customerEmail = 'Dear' . $application->name . ',<br/>🎉 Congrats! You are pre-approved up to Rs' . str_replace('.00', '', money_format('%!i', $application->loan_amount)) . '<br/><br/>Please note that the final loan amount and offer might change.*The pre-approval will expire on ' . $date . '.*';

                }

                \Mail::send('emails.reminders.basic_reminder', [
                    'body' => $customerEmail,
                ], function ($message) use ($application, $subject) {
                    $message->to($application->email)->subject($subject);
                    $message->cc('centralops@creditfair.in');
                });
            }
        }

        $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 ($application->mobile_number) {
            // if ($_listString) {

//                $sms = 'Dear ' . $application->name . ',<br/>
//🎉 Congrats! You are pre-approved up to Rs ' . str_replace('.00', '', money_format('%!i', $application->loan_amount)) . ' subject to submission of following documents:<br/><br/>' . $_listString . '<br/>Please note that the final loan amount and offer might differ.*The pre-approval will expire on ' . $date . '*.<br/>
//Regards,
//Team Credit Fair';

            //     $sms = 'Dear ' . $application->name . ',<br/> Congrats! Your pre-approved loan up to Rs.' . str_replace('.00', '', money_format('%!i', $application->loan_amount)) . ' is ready for approval, subject to submission of KYC documents. Kindly note that the loan amount offer may change depending on your credit profile. Get it now  '.$consumer_app_link.' before it expires on ' . $date .' <br/> - Credit Fair';
            //     $entity = ['templateid' => '1307166902857184800', 'entityid' => Templates::$entityid];
            // } else {

                $sms = 'Dear ' . $application->name . ',<br/> Congrats! Your pre-approved loan up to Rs.' . str_replace('.00', '', money_format('%!i', $application->loan_amount)) . ' is ready for approval, subject to submission of KYC documents. Kindly note that the loan amount offer may change depending on your credit profile. Get it now  '.$consumer_app_link.' before it expires on ' . $date .' <br/> - Credit Fair';
                $entity = ['templateid' => '1307166902857184800', 'entityid' => Templates::$entityid];
            // }

            $sms = str_replace('<br/>', "\n", $sms);
            $sms = str_replace('<br>', "\n", $sms);

            $templateId = Templates::$pre_approval_c1;
            $args = [$application->name, str_replace('.00', '', money_format('%!i', $application->loan_amount)), $consumer_app_link, $date];

            //send_sms($application->mobile_number, ['message' => $sms, 'id' => $application_id, 'id_type' => 'application_id', 'templateId' => $templateId, 'args' => $args, 'templateDetails' => $entity]);
        }


        if ($application->merchant && $application->merchant->email && (!in_array($application->merchant_id, explode(',', _env('NO_COMM_MERCHANT'))))) {
            $subject = "👍" . $application->name . " has been Pre-Approved for their purchase of " . $application->loan_amount . "!";

            if ($_listString) {

                $merchantEmail = 'Dear ' . $application->merchant->merchant_name . ',<br/><br/>Congrats! ' . $application->name . ' has been pre-approved up to Rs ' . str_replace('.00', '', money_format('%!i', $application->loan_amount)) . " subject to submission of following documents:<br/><br/>" . $_listString . "<br/><br/>Please note that the final loan amount and offer might differ.*The pre-approval will expire on " . $date . '.*';

            } else {

                $merchantEmail = 'Dear ' . $application->merchant->merchant_name . ',<br/>👍 Congrats! ' . $application->name . ' has been pre-approved up to Rs ' . str_replace('.00', '', money_format('%!i', $application->loan_amount)) . '<br/><br/>Please note that the final amount might change.*The pre-approval will expire on ' . $date . '.*<br/><br/>Warning: Don’t deliver product/service until we have disbursed the funds.';

            }


            if (strpos($application->merchant->email, ',') !== false) {
                $emails = explode(',', $application->merchant->email);
            } else {
                $emails = $application->merchant->email;
            }

//            \Mail::send('emails.reminders.basic_reminder', [
//                'body' => $merchantEmail,
//            ], function ($message) use ($emails, $subject) {
//                $message->to($emails)->subject($subject);
//                $message->cc('centralops@creditfair.in');
//            });
        }


        if ($application->merchant && $application->merchant->contact_number && (!in_array($application->merchant_id, explode(',', _env('NO_COMM_MERCHANT'))))) {
            if ($_listString) {
//                $sms = "Dear " . $application->merchant->merchant_name . ",
//👍 Congrats! " . $application->name . " has been pre-approved up to Rs " . str_replace('.00', '', money_format('%!i', $application->loan_amount)) . " subject to submission of following documents:\n
//" . $_listString . "
//Please note that the final amount might vary. *The pre-approval will expire on " . $date . ".*\n
//*Warning: Don’t deliver product/service until we have sent disbursement of funds.*
//Regards,
//Team Credit Fair\n
//";

                $sms = "Dear " . $application->merchant->merchant_name . ",
👍 Congrats! " . $application->name . " has been pre-approved up to Rs." . str_replace('.00', '', money_format('%!i', $application->loan_amount)) . "subject to submission of KYC documents. Kindly note that the loan amount offer may change depending on the credit profile. The pre-approval will expire on " . $date . ".*\n*Warning: Dont deliver product/service until we have sent disbursement of funds.*";
            } else {
                $sms = 'Dear ' . $application->merchant->merchant_name . ',<br/>
👍 Congrats! ' . $application->name . ' has been pre-approved up to Rs' . str_replace('.00', '', money_format('%!i', $application->loan_amount)) . '<br/><br/>Please note that the final amount might vary. The pre-approval will expire on ' . $date . '<br/><br/>Warning: Don’t deliver product/service until we have disbursed the funds.<br/>
Regards,
Team Credit Fair';
            }
            $templateId = Templates::$pre_approved_merchant_02;
            $args = [$application->merchant->merchant_name, $application->name, str_replace('.00', '', money_format('%!i', $application->loan_amount)), $_listString, $date];
            //send_sms($application->merchant->contact_number, ['message' => $sms, 'id' => $application_id, 'id_type' => 'application_id', 'templateId' => $templateId, 'args' => $args]);


        }
    }

    public function sendAutoPreApprovalCommunication($application_id){
        $application = ConsumerApplication::with('merchant', 'application_element', 'documents')->where('id', $application_id)->first();


        //for credit team mailer
        $_merchant = optional(Merchant::find($application->merchant_id))->merchant_name ?? "";
        $advisor_name = optional(User::find($application->created_by))->name ?? "";
        $offer_details = MerchantOffers::where('id', $application->offer_id)->first();
        $net_loan_amount = (new FrontController())->checkNetLoanAmount($offer_details, $application->approved_amount);
        $credit_body = "Customer Name: ".$application->name."<br>Merchant Name: ".$_merchant."<br>Advisor Name: ".$advisor_name."<br>Application Link: <a href=".asset("admin/consumer-applications/edit/".$application->id).">Click Here</a><br>Status: Pre Approved<br><br>Regards,<br>Team Credit Fair";
        $credit_manager_emails = User::wherenull('deleted_at')->wherenotnull('credit_approval_limit')->where('credit_approval_limit', '>=', $net_loan_amount)->whereIn('user_type', [_env('CREDIT_TEAM_USER_TYPE'), _env('SENIOR_CREDIT_TEAM_USER_TYPE')])->get(['email'])->pluck('email');
        if($credit_manager_emails->isNotEmpty()) {
            $credit_recipients = $credit_manager_emails->toArray();
            Mail::send('emails.reminders.basic_reminder',
                ['body' => $credit_body]
                , function ($message) use ($credit_recipients, $net_loan_amount) {
                    $message->to($credit_recipients)->subject("Pre Approved Net Loan Amount ₹".$net_loan_amount);
                });
        }
        //for credit team slack notif
        try{
            $lender_name = optional(Lenders::find($application->lender_id))->name ?? "";
            (new Slack(new Request(['title' => 'New Application Pre Approved', 'fields' => ['Customer Name' => $application->name,'Net Loan Amount'=>$net_loan_amount, 'Merchant Name'=>$_merchant, 'Application link'=>asset("admin/consumer-applications/edit/".$application->id), 'Lender'=>$lender_name], 'group' => Slack::$CRED_TEAM_SOFT_APPROVAL])))->send();
        }
        catch (\Exception $e){
            (new Slack(new Request(['title' => 'slack notif for pre approval job creation failed', 'fields' => ['e' => $e->getMessage(),'l' => $e->getLine(),'t' => $e->getTraceAsString(), 'id' => $application->id], 'group' => Slack::$STAGE_TESTING])))->send();
        }
    }

    public function sendemandate($application_id)
    {
        return false;
        $emandate = Mandate::where('mode', 'lotuspay_emandate')->where('consumer_application_id', $application_id)->where('status', '!=', 'withdrawn')->where('status', '!=', 'rejected')->get();
        if (!$emandate) {
            $bank = Bank::where('application_id', $application_id)->first();

            if ($bank) {
                $bank_names = array_keys(\Illuminate\Support\Facades\Config::get('constants.emandate_bank_list'));
                if (in_array($bank->bank_name, $bank_names)) {
                    $request = new Request();
                    $request->request->add([
                        'type' => 'Bank-Details',
                        'bot' => true,
                        'request_type' => 'Send Email'
                    ]);
                    $document = (new ConsumerDocument($request));
                    $documentDetails = $document->getDocument($application_id);

                    if (!is_array($documentDetails)) {
                        return $documentDetails;
                    }

                    $data = [
                        'txt' => view('emails.consumer_activation_mail_bank', $documentDetails),
                        'body' => view('emails.consumer_activation_mail_bank', $documentDetails),
                        'subject' => 'Auto Debit (E-NACH) Registration'
                    ];

                    $request->request->add($data);

                    $document->downloadDocument($application_id);

                    return 1;
                }
            }
        }
        $mandate = Mandate::where('mode', 'lotuspay_physical')->where('consumer_application_id', $application_id)->where('status', '!=', 'withdrawn')->where('status', '!=', 'rejected')->get();
        if (!$mandate) {
            $bank = Bank::where('application_id', $application_id)->first();

            if ($bank) {
                $nach = new \App\Http\Controllers\NachController();
                $response = $nach->createMandate($application_id, 'physical', 'MNTH');
                $response = $nach->createMandate($application_id, 'physical', 'ADHO');
            }
        }
        return 1;
    }

    public function sendClosureLetter($application_id)
    {
        $request = new Request();
        $request->request->add([
            'type' => "Closures Letters",
            'bot' => true
        ]);
        $document = (new ConsumerDocument($request));
        $documentDetails = $document->getDocument($application_id);
        $data = [
            'txt' => view('admin.documents.closure_letter', $documentDetails),
            'body' => view('emails.reminders.closure_letter', $documentDetails),
            'subject' => 'Closure of Your Loan (Agreement Number - ' . $documentDetails['user']['application_id'] . ')'
        ];
        if(($documentDetails['is_bnpl'] == 1) || in_array($documentDetails['user']['merchant_id'],[6418,6517,6598,6865,6600])){
            $data['subject'] = '';
        }

        $request->request->add($data);
        $document->downloadDocument($application_id);
    }

    public function sendSettlementLetter($application_id, $fetchPDF=true) {
        $request = new Request();
        $request->request->add([
            'type' => 'Settlement Letters',
            'bot' => true
        ]);
        $document = (new ConsumerDocument($request));
        $documentDetails = $document->getDocument($application_id);
        $data = [
            'txt' => view('admin.documents.settlement_letter', $documentDetails),
            'body' => view('emails.reminders.settlement_letter', $documentDetails),
            'subject' => 'Settlement Letter of Your Loan (Agreement Number - ' . $documentDetails['user']['application_id'] . ')'
        ];

        if ($fetchPDF) {
            $pdf = App::make('snappy.pdf.wrapper');
            $pdf->loadHTML($data['txt'])->setOption('encoding', 'UTF-8')->setPaper('a4')->setOrientation('portrait');
            $pdf->setOption('margin-bottom', 25);
            $loan_agreement = $pdf->setOption('footer-html', view('admin.editor.footer', ['type' => 'Settlement Letters', 'lender' => $documentDetails['lender']])->render());
            return $loan_agreement->download('Settlement_Letter.pdf');
        }
        else {
            $request->request->add($data);
            $document->downloadDocument($application_id);
        }
    }

    public function downloadClosureLetter($application_id)
    {
        $request = new Request();
        $request->request->add([
            'type' => 'Closures Letters',
            'bot' => true
        ]);
        $document = (new ConsumerDocument($request));
        $documentDetails = $document->getDocument($application_id);
        $data = [
            'txt' => view('admin.documents.closure_letter', $documentDetails),
            'body' => view('emails.reminders.closure_letter', $documentDetails),
            'subject' => 'Closure of Your Loan (Agreement Number - ' . $documentDetails['user']['application_id'] . ')'
        ];

        $pdf = App::make('snappy.pdf.wrapper');
        $pdf->loadHTML($data['txt'])->setOption('encoding', 'UTF-8')->setPaper('a4')->setOrientation('portrait');
        $pdf->setOption('margin-bottom', 25);
        $loan_agreement = $pdf->setOption('footer-html', view('admin.editor.footer', ['type' => 'Closures Letters', 'lender' => $documentDetails['lender']])->render());
        return $loan_agreement->download('Closures_Letter.pdf');
    }

    public function getListOfDocuments($application)
    {
        $co_applicant_employee_status = $application->co_applicant_employee_status;
        $employee_status = $application->employee_status;
        $list = '<ul>';
        if ($employee_status == 'SALARIED') {
            $list .= '<li>3 months salary Slip</li>';
        } elseif ($employee_status == 'BUSINESS') {
            $list .= '<li>Latest 2 years ITR including Computation of Income/P&L Account/Balance Sheet certified by a CA.</li>';
        } else {
            if ($co_applicant_employee_status == 'SALARIED') {
                $list .= '<li>Co-applicant Latest 3 month\'s Salary Slips</li>';
            } elseif ($co_applicant_employee_status == 'BUSINESS') {
                $list .= '<li>Co-applicant Latest 2 years ITR including Computation of Income/P&L Account/Balance Sheet certified by a CA.</li>';
            }
        }
        $list .= '<li>Bank statements for the last 6 months in PDF format</li>';
        $list .= '<li>PAN card copy (self attested)</li>';
        $list .= '<li>Aadhaar card copy (self attested)</li>';
        $list .= '<li>Electricity bill for your residence</li>';
        $list .= '</ul>';
        return $list;
    }

    public function rollbackJobChanges($data, $status, $statusArray = array())
    {

        $statusArray = array_merge($statusArray, ['waiting for decision']);
        $application_id = $data['application_id'];
        if (in_array($status, $statusArray)) {
            $first_reminder = JobProvider::where('application_id', $application_id)->where('from', 'applicationEscalation')->where('payload', 'like', '%"action":"first_reminder"%')->first(['id']);
            if (isset($first_reminder->id)) {
                JobProvider::where('id', $first_reminder->id)->delete();
            }

            $final_reminder = JobProvider::where('application_id', $application_id)->where('from', 'applicationEscalation')->where('payload', 'like', '%"action":"final_reminder"%')->first(['id']);
            if (isset($final_reminder->id)) {
                JobProvider::where('id', $final_reminder->id)->delete();
            }

            $aborted = JobProvider::where('application_id', $application_id)->where('from', 'applicationEscalation')->where('payload', 'like', '%"action":"aborted"%')->first(['id']);
            if (isset($aborted->id)) {
                JobProvider::where('id', $aborted->id)->delete();
            }
        }
    }

    public function getEscalationRules($amount = 0, $type = 0)
    {
        $rules = [['amount' => [0, 75000], 'time' => [3, 4]], ['amount' => [75000, 150000], 'time' => [5, 6]], ['amount' => [150000, 20000000], 'time' => [7, 8]]];
        if ($amount) {
            return array_map(function ($rule) use ($amount, $type) {
                return ($amount > $rule['amount'][0] && $amount <= $rule['amount'][1]) ? $rule['time'][$type] : 0;
            }, $rules);
        }
        return $rules;
    }

    public function startEscalation($application_id, $status, $amount = 0)
    {

        $isAborted = StatusLogs::where('application_id', $application_id)->where('status','aborted')->first(['id']);
        if (isset($isAborted->id)){
            return false;
        }
        $this->rollbackJobChanges(['application_id' => $application_id], $status, [$status]);

        $application = ConsumerApplication::with('merchant', 'advisor')->where('id', $application_id)->first();
        if ($application) {
            $messages = [];

            $schedules = $this->getEscalationRules();

            $loan_amount = $amount > 0 ? $amount : $application->loan_amount;

            if ($status == 'waiting for documents' || $status == 'in-process') {

                foreach ($schedules as $schedule) {
                    if ($loan_amount > $schedule['amount'][0] && $loan_amount <= $schedule['amount'][1]) {
                        if($status == 'waiting for documents') {
                            //$hashids = new Hashids('Creditfair by CS', 20);
                            $expiry = date('d M, Y', strtotime(Carbon::now()->addDays($schedule['time'][1])->endOfDay()->toDateTimeString()));
                            //$link = \Bitly::getUrl(asset("esign/id/" . $hashids->encode($application_id)));
                            //customer

                            $documents = $this->getListOfDocuments($application);
                            $sinceDay = $schedule['time'][0];

                            $templateId = Templates::$pending_doc_c1;
                            $args = [$application->name, $expiry];

                            $messages[] = [
                                'subject' => 'Documents pending since ' . $sinceDay . ' days for your loan application to purchase from ' . $application->merchant->merchant_name,
//                            'sms' => 'Dear ' . $application->name . ',<br/>Kindly note that the your loan application will expire ' . $expiry . ', upon not receiving the required documents. A complete loan application can improve your credit score. Therefore, we would advise you to send in the documents at the earliest. Let us know if you have any questions.<br/>Best Regards,<br/>Team Credit Fair',
                                'sms' => 'Dear ' . $application->name . ', <br/>Documents pending for submission. Send them over to ops@creditfair.in to get approval within 5 mins. The application aborts on ' . $expiry . '. <br/> - Credit Fair',
                                'templateId' => $templateId,
                                'args' => $args,
                                'templateDetails' => ['templateid' => '1307166902839939589', 'entityid' => Templates::$entityid],
                                'action' => 'first_reminder',
                                'advisorEmail' => $application->advisor->email,
                                'advisorSlack' => isset($application->advisor->slack_url) ? $application->advisor->slack_url : null,
                                'body' => 'Dear ' . $application->name . ',<br/>
                                    This is a gentle reminder to complete your loan application to complete your purchase from ' . $application->merchant->merchant_name . '. Please send the following documents at your earliest convenience:<br/>
                                    ' . $documents . '
                                    Please note that a completed loan application could improve your credit score. Feel free to contact us at +91 9967235047 or email us on ops@creditfair.in. We would love to hear from you!
                                    <br/><br/>Regards,<br/>Team Credit Fair',
                                'available_at' => Carbon::now()->addDays($schedule['time'][0])->toDateString() . ' 13:00:00',
                            ];
                            $sinceDay = $schedule['time'][1];
                            //merchant
                            $messages[] = [
                                'subject' => 'Last reminder - Documents pending since ' . $sinceDay . ' days for your loan application to purchase from ' . $application->merchant->merchant_name,
//                            'sms' => 'Dear ' . $application->name . ',<br/>Kindly note that the your loan application will expire ' . $expiry . ', upon not receiving the required documents. A complete loan application can improve your credit score. Therefore, we would advise you to send in the documents at the earliest. Let us know if you have any questions.<br/>Best Regards,<br/>Team Credit Fair',
                                'sms' => 'Dear ' . $application->name . ', <br/>Documents pending for submission. Send them over to ops@creditfair.in to get approval within 5 mins. The application aborts on ' . $expiry . '. <br/> - Credit Fair',
                                'templateId' => $templateId,
                                'args' => $args,
                                'templateDetails' => ['templateid' => '1307166902839939589', 'entityid' => Templates::$entityid],
                                'action' => 'final_reminder',
                                'body' => 'Dear ' . $application->name . ',<br/>This is a gentle reminder to complete your loan application for your purchase from ' . $application->merchant->merchant_name . '. Please ensure following documents have been sent at your earliest convenience:<br/>
                                    ' . $documents . '
                                    Please note that a completed loan application could improve your credit score. Feel free to contact us at +91 9967235047 or email us on ops@creditfair.in.<br/><br/>
                                    If we don’t hear back we will assume that you want to cancel your loan application.<br/>
                                    <br/>
                                    Regards,<br/>
                                    Team Credit Fair',
                                'available_at' => Carbon::now()->addDays($schedule['time'][1])->toDateString() . ' 13:00:00',
                            ];
                        }
                        if (($status == 'waiting for documents' || $status == 'in-process') && isset($application->merchant) && $application->merchant->is_auto_abort == 1) {
                            //auto abort
                            $messages[] = [
                                'action' => 'aborted',
                                'available_at' => Carbon::now()->addDays($schedule['time'][1] + 1)->toDateString() . ' 12:00:00'
                            ];

                        }
                        break;
                    }
                }


            } else if ($status == 'waiting for decision') {
                //advisor
                /*$messages[] = [
                    'subject' => '',
                    'body' => 'The '.$application->name.'\'s application from '.$application->merchant->merchant_name.' is been '.$status.' for last 30 minutes. Please clear the case on priority.',
                    'action' => 'email',
                    'type'=>'advisor',
                    'available_at' => Carbon::now()->addDays(30)->toDateString() . ' 13:00:00',
                ];*/

                //credit manager
                if(isset($application->name) && $application->name) {
                    $messages[] = [
                        'subject' => 'Application of ' . $application->name . ' is waiting for decision',
                        'body' => 'The ' . $application->name . '\'s application from ' . $application->merchant->merchant_name . ' managed by ' . $application->advisor->name . ' is been ' . $status . ' for last 30 minutes. Please follow up on the case on priority.',
                        'action' => 'email',
                        'type' => 'credit',
                        'available_at' => Carbon::now()->addMinutes(30)->toDateTimeString()
                    ];
                }
            }
            if ($messages) {
                foreach ($messages as $item) {
                    $payload[] = [
                        'payload' => json_encode($item),
                        'from' => 'applicationEscalation',
                        'application_id' => $application_id,
                        'available_at' => $item['available_at'],
                        'created_at' => Carbon::now()->toDateTimeString()
                    ];
                }
                if (isset($payload)) {
                    $job = new Jobs();
                    $job->insertQueue($payload);
                }
            }
        }
    }

    public function isProcessingFeeApplicable($application_id)
    {
        return $this->isExistingCustomer($application_id, true);
    }

    public function getCachedExistingCustomer($id, $processing_fee){
        $cacheExistingCustomer = CacheExistingCustomer::where(['application_id' => $id, 'processing_fee' => (int)$processing_fee])->first(['id','status', 'matched', 'processing_fee']);
        if(isset($cacheExistingCustomer->id)){
            return [
                'status' => $cacheExistingCustomer->status,
                'matched' => $cacheExistingCustomer->matched
            ];
        }

        return false;
    }

    public function updateCachedExistingCustomer($application, Request $request){
        $status = false;
        if($request->get('pan_card') && $application->pan_card != $request->get('pan_card')){
            $status = true;
        }else if($request->get('co_applicant_pan_card') && $application->co_applicant_pan_card != $request->get('co_applicant_pan_card')){
            $status = true;
        }else if($request->get('email') && $application->email != $request->get('email')){
            $status = true;
        }else if($request->get('co_applicant_email') && $application->co_applicant_email != $request->get('co_applicant_email')){
            $status = true;
        }else if($request->get('mobile_number') && $application->mobile_number != $request->get('mobile_number')){
            $status = true;
        }else if($request->get('co_applicant_mobile_number') && $application->co_applicant_mobile_number != $request->get('co_applicant_mobile_number')){
            $status = true;
        }else if($request->get('aadhaar_card') && $application->aadhaar_card != $request->get('aadhaar_card')){
            $status = true;
        }else if($request->get('co_applicant_aadhaar_card') && $application->co_applicant_aadhaar_card != $request->get('co_applicant_aadhaar_card')){
            $status = true;
        }

        if($status){
            CacheExistingCustomer::where('application_id', $application->id)->delete();
        }
    }

    public function updateCacheExistingCustomer($id, $status, $matched, $processing_fee){
        $matchedIds = [];
        if($matched) {
            foreach ($matched as $key => $value) {
                $matchedIds[] = $value->id.'|'.$key;
            }
        }
        CacheExistingCustomer::where(['application_id' => $id, 'processing_fee' => (int)$processing_fee])->delete();
        $cacheExistingCustomer = new CacheExistingCustomer();
        $cacheExistingCustomer->fill(
            [
            'application_id' => $id,
            'status' => $status,
            'matched' => implode(',',$matchedIds),
            'processing_fee' => (int)$processing_fee,
            ]
        );

        $cacheExistingCustomer->save();
    }

    public function getMatchedDataList($matched){
        $matchedData = explode(',', $matched);
        $appIds = [];
        if($matchedData) {
            foreach ($matchedData as $matchedItem) {
                $matchedItemSegment = explode('|', $matchedItem);
                if(isset($matchedItemSegment[1])) {
                    $appIds[$matchedItemSegment[0]] = $matchedItemSegment[1];
                }
            }
        }

        $existing = [];
        $applications = ConsumerApplication::whereIn('id', array_keys($appIds))->get(['id', 'name']);
        foreach($applications as $application){
            $existing[$appIds[$application->id]] = $application;
        }

        return $existing;
    }

    public function isExistingCustomer($application_id, $isProcessingCheck = false, $statusArray = array())
    {
        $status = false;
        $existing = [];
        $statusArray = $isProcessingCheck ? ['disbursed', 'closed', 'nach registered'] : ($statusArray ? $statusArray : []);

        $application = ConsumerApplication::with('merchant')->where('id', $application_id)->first();
        if (!$application) {
            return false;
        }


        $getCachedExistingCustomer = $this->getCachedExistingCustomer($application->id, $isProcessingCheck);
        if($getCachedExistingCustomer){
            $status = $getCachedExistingCustomer['status'];
            $existing = $this->getMatchedDataList($getCachedExistingCustomer['matched']);
        }else {
            $ignoreValues = ['NA', 'N/A', 'NULL', '-'];
            if ((isset($application->pan_card) && $application->pan_card)) {
                $panCard = trim($application->pan_card);
                if (!in_array(strtoupper($panCard), $ignoreValues)) {
                    $is_existing = ConsumerApplication::where('id', '!=', $application_id)->where('pan_card', $panCard)->whereNull('is_deleted');
                    $co_app_is_existing = ConsumerApplication::where('id', '!=', $application_id)->where('co_applicant_pan_card', $panCard)->whereNull('is_deleted');

                    if ($statusArray) {
                        $is_existing->whereIn('state', $statusArray);
                        $co_app_is_existing->whereIn('state', $statusArray);
                    }
                    $is_existing = $is_existing->first(['id', 'state', 'name', 'merchant_id']);
                    $co_app_is_existing = $co_app_is_existing->first(['id', 'state', 'name', 'merchant_id']);

                    if ($is_existing && (empty($statusArray) || in_array($is_existing->state, $statusArray)) && (isset($is_existing->merchant_id) && $this->isNonBreMerchant($is_existing->merchant_id))) {
                        $status = true;
                        $existing['Pan Card'] = $is_existing;
                    }

                    if ($co_app_is_existing && (empty($statusArray) || in_array($co_app_is_existing->state, $statusArray)) && (isset($co_app_is_existing->merchant_id) && $this->isNonBreMerchant($co_app_is_existing->merchant_id))) {
                        $status = true;
                        $existing['Co-App Pan Card'] = $co_app_is_existing;
                    }
                }
            }
            if ((isset($application->email) && $application->email)) {
                $email = trim($application->email);

                $is_existing = ConsumerApplication::where('id', '!=', $application_id)->where('email', $email)->whereNull('is_deleted');
                $co_app_is_existing = ConsumerApplication::where('id', '!=', $application_id)->where('co_applicant_email', $email)->whereNull('is_deleted');
                if ($statusArray) {
                    $is_existing->whereIn('state', $statusArray);
                    $co_app_is_existing->whereIn('state', $statusArray);
                }
                $is_existing = $is_existing->first(['id', 'state', 'name', 'merchant_id']);
                $co_app_is_existing = $co_app_is_existing->first(['id', 'state', 'name', 'merchant_id']);

                if ($is_existing && (empty($statusArray) || in_array($is_existing->state, $statusArray)) && (isset($is_existing->merchant_id) && $this->isNonBreMerchant($is_existing->merchant_id))) {
                    $status = true;
                    $existing['Email'] = $is_existing;
                }

                if ($co_app_is_existing && (empty($statusArray) || in_array($co_app_is_existing->state, $statusArray)) && (isset($co_app_is_existing->merchant_id) && $this->isNonBreMerchant($co_app_is_existing->merchant_id))) {
                    $status = true;
                    $existing['Co-App Email'] = $co_app_is_existing;
                }
            }
            if ((isset($application->mobile_number) && $application->mobile_number)) {
                $mobile = trim($application->mobile_number);

                $is_existing = ConsumerApplication::where('id', '!=', $application_id)->where('mobile_number', $mobile)->whereNull('is_deleted');
                $co_app_is_existing = ConsumerApplication::where('id', '!=', $application_id)->where('co_applicant_mobile_number', $mobile)->whereNull('is_deleted');
                if ($statusArray) {
                    $is_existing->whereIn('state', $statusArray);
                    $co_app_is_existing->whereIn('state', $statusArray);
                }
                $is_existing = $is_existing->first(['id', 'state', 'name', 'merchant_id']);
                $co_app_is_existing = $co_app_is_existing->first(['id', 'state', 'name', 'merchant_id']);

                if ($is_existing && (empty($statusArray) || in_array($is_existing->state, $statusArray)) && (isset($is_existing->merchant_id) && $this->isNonBreMerchant($is_existing->merchant_id))) {
                    $status = true;
                    $existing['Mobile No.'] = $is_existing;
                }
                if ($co_app_is_existing && (empty($statusArray) || in_array($co_app_is_existing->state, $statusArray)) && (isset($co_app_is_existing->merchant_id) && $this->isNonBreMerchant($co_app_is_existing->merchant_id))) {
                    $status = true;
                    $existing['Co-App Mobile No.'] = $co_app_is_existing;
                }
            }
            if ((isset($application->aadhaar_card) && $application->aadhaar_card)) {
                $aadhaar = trim($application->aadhaar_card);

                $is_existing = ConsumerApplication::where('id', '!=', $application_id)->where('aadhaar_card', $aadhaar)->whereNull('is_deleted');
                $co_app_is_existing = ConsumerApplication::where('id', '!=', $application_id)->where('co_applicant_aadhaar_card', $aadhaar)->whereNull('is_deleted');
                if ($statusArray) {
                    $is_existing->whereIn('state', $statusArray);
                    $co_app_is_existing->whereIn('state', $statusArray);
                }
                $is_existing = $is_existing->first(['id', 'state', 'name', 'merchant_id']);
                $co_app_is_existing = $co_app_is_existing->first(['id', 'state', 'name', 'merchant_id']);

                if ($is_existing && (empty($statusArray) || in_array($is_existing->state, $statusArray)) && (isset($is_existing->merchant_id) && $this->isNonBreMerchant($is_existing->merchant_id))) {
                    $status = true;
                    $existing['Aadhaar Card'] = $is_existing;
                }
                if ($co_app_is_existing && (empty($statusArray) || in_array($co_app_is_existing->state, $statusArray)) && (isset($co_app_is_existing->merchant_id) && $this->isNonBreMerchant($co_app_is_existing->merchant_id))) {
                    $status = true;
                    $existing['Co-App Aadhaar Card'] = $co_app_is_existing;
                }
            }
            if (isset($application->co_applicant_pan_card) && $application->co_applicant_pan_card) {
                $coPanCard = trim($application->co_applicant_pan_card);
                if (!in_array(strtoupper($coPanCard), $ignoreValues)) {
                    $is_existing = ConsumerApplication::where('id', '!=', $application_id)->where('pan_card', $coPanCard)->whereNull('is_deleted');
                    $co_app_is_existing = ConsumerApplication::where('id', '!=', $application_id)->where('co_applicant_pan_card', $coPanCard)->whereNull('is_deleted');
                    if ($statusArray) {
                        $is_existing->whereIn('state', $statusArray);
                        $co_app_is_existing->whereIn('state', $statusArray);
                    }
                    $is_existing = $is_existing->first(['id', 'state', 'name', 'merchant_id']);
                    $co_app_is_existing = $co_app_is_existing->first(['id', 'state', 'name', 'merchant_id']);

                    if ($is_existing && (empty($statusArray) || in_array($is_existing->state, $statusArray)) && (isset($is_existing->merchant_id) && $this->isNonBreMerchant($is_existing->merchant_id))) {
                        $status = true;
                        $existing['Pan Card'] = $is_existing;
                    }

                    if ($co_app_is_existing && (empty($statusArray) || in_array($co_app_is_existing->state, $statusArray)) && (isset($co_app_is_existing->merchant_id) && $this->isNonBreMerchant($co_app_is_existing->merchant_id))) {
                        $status = true;
                        $existing['Co-App Pan Card'] = $co_app_is_existing;
                    }
                }
            }
            if (isset($application->co_applicant_email) && $application->co_applicant_email) {
                $coEmail = trim($application->co_applicant_email);

                $is_existing = ConsumerApplication::where('id', '!=', $application_id)->where('email', $coEmail)->whereNull('is_deleted');
                $co_app_is_existing = ConsumerApplication::where('id', '!=', $application_id)->where('co_applicant_email', $coEmail)->whereNull('is_deleted');
                if ($statusArray) {
                    $is_existing->whereIn('state', $statusArray);
                    $co_app_is_existing->whereIn('state', $statusArray);
                }
                $is_existing = $is_existing->first(['id', 'state', 'name', 'merchant_id']);
                $co_app_is_existing = $co_app_is_existing->first(['id', 'state', 'name', 'merchant_id']);

                if ($is_existing && (empty($statusArray) || in_array($is_existing->state, $statusArray)) && (isset($is_existing->merchant_id) && $this->isNonBreMerchant($is_existing->merchant_id))) {
                    $status = true;
                    $existing['Email'] = $is_existing;
                }

                if ($co_app_is_existing && (empty($statusArray) || in_array($co_app_is_existing->state, $statusArray)) && (isset($co_app_is_existing->merchant_id) && $this->isNonBreMerchant($co_app_is_existing->merchant_id))) {
                    $status = true;
                    $existing['Co-App Email'] = $co_app_is_existing;
                }
            }
            if (isset($application->co_applicant_mobile_number) && $application->co_applicant_mobile_number) {
                $coMobile = trim($application->co_applicant_mobile_number);

                $is_existing = ConsumerApplication::where('id', '!=', $application_id)->where('mobile_number', $coMobile)->whereNull('is_deleted');
                $co_app_is_existing = ConsumerApplication::where('id', '!=', $application_id)->where('co_applicant_mobile_number', $coMobile)->whereNull('is_deleted');
                if ($statusArray) {
                    $is_existing->whereIn('state', $statusArray);
                    $co_app_is_existing->whereIn('state', $statusArray);
                }
                $is_existing = $is_existing->first(['id', 'state', 'name', 'merchant_id']);
                $co_app_is_existing = $co_app_is_existing->first(['id', 'state', 'name', 'merchant_id']);

                if ($is_existing && (empty($statusArray) || in_array($is_existing->state, $statusArray)) && (isset($is_existing->merchant_id) && $this->isNonBreMerchant($is_existing->merchant_id))) {
                    $status = true;
                    $existing['Mobile No.'] = $is_existing;
                }
                if ($co_app_is_existing && (empty($statusArray) || in_array($co_app_is_existing->state, $statusArray)) && (isset($co_app_is_existing->merchant_id) && $this->isNonBreMerchant($co_app_is_existing->merchant_id))) {
                    $status = true;
                    $existing['Co-App Mobile No.'] = $co_app_is_existing;
                }
            }
            if (isset($application->co_applicant_aadhaar_card) && $application->co_applicant_aadhaar_card) {
                $coAadhaar = trim($application->co_applicant_aadhaar_card);

                $is_existing = ConsumerApplication::where('id', '!=', $application_id)->where('aadhaar_card', $coAadhaar)->whereNull('is_deleted');
                $co_app_is_existing = ConsumerApplication::where('id', '!=', $application_id)->where('co_applicant_aadhaar_card', $coAadhaar)->whereNull('is_deleted');
                if ($statusArray) {
                    $is_existing->whereIn('state', $statusArray);
                    $co_app_is_existing->whereIn('state', $statusArray);
                }
                $is_existing = $is_existing->first(['id', 'state', 'name', 'merchant_id']);
                $co_app_is_existing = $co_app_is_existing->first(['id', 'state', 'name', 'merchant_id']);

                if ($is_existing && (empty($statusArray) || in_array($is_existing->state, $statusArray)) && (isset($is_existing->merchant_id) && $this->isNonBreMerchant($is_existing->merchant_id))) {
                    $status = true;
                    $existing['Aadhaar Card'] = $is_existing;
                }
                if ($co_app_is_existing && (empty($statusArray) || in_array($co_app_is_existing->state, $statusArray)) && (isset($co_app_is_existing->merchant_id) && $this->isNonBreMerchant($co_app_is_existing->merchant_id))) {
                    $status = true;
                    $existing['Co-App Aadhaar Card'] = $co_app_is_existing;
                }
            }
            $this->updateCacheExistingCustomer($application_id, $status, $existing, $isProcessingCheck);
        }

        $isGood = true;
        $repeat_list = '';
        if ($isProcessingCheck) {
            $isGood = false;
            if ($application->merchant && $application->merchant->is_processing_fees == 1) {
                $isGood = true;
            }
        }

        if ($status && $isGood) {
            if($isProcessingCheck){
                return true;
            }else{
                foreach($existing as $key => $value){
                    $repeat_list .= $value->id . ' - ' . $value->name . ' [' . $key . ']'."\n<br>"; /*Something needs to be added here cna't seem to add a break or preview the text*/
                }
                return $repeat_list;
            }
        }

        return false;
    }

    public function isNonBreMerchant($merchant_id)
    {
        if ($merchant_id) {
            $merchant = DB::selectOne("SELECT id, status from merchant where id = ?", [$merchant_id]);
            return $merchant->status != 'bre';
        }
        return false;
    }

    public function isExistingCustomerDeprecated($application_id, $isProcessingCheck = false, $statusArray = array())
    {
        $status = false;
        $existing = [];
        $statusArray = $isProcessingCheck ? ['disbursed', 'closed', 'nach registered'] : ($statusArray ? $statusArray : []);
        $application = ConsumerApplication::with('merchant')->where('id', $application_id)->first();
        if ((isset($application->pan_card) && $application->pan_card)) {
            $is_existing = ConsumerApplication::where('id', '!=', $application_id)->where('pan_card', 'like', '%'.trim($application->pan_card).'%');
            $co_app_is_existing = ConsumerApplication::where('id', '!=', $application_id)->where('co_applicant_pan_card', 'like', '%'.trim($application->pan_card).'%');

            if ($statusArray) {
                $is_existing = $is_existing->whereIn('state', $statusArray);
                $co_app_is_existing = $co_app_is_existing->whereIn('state', $statusArray);
            }

            $is_existing = $is_existing->whereNull('is_deleted')->first(['id', 'state', 'name']);
            $co_app_is_existing = $co_app_is_existing->whereNull('is_deleted')->first(['id', 'state', 'name']);
            if (isset($is_existing->id) && (empty($statusArray) || (in_array($is_existing->state, $statusArray)))) {
                $status = true;
                $existing['Pan Card'] = $is_existing;
            }

            if (isset($co_app_is_existing->id) && (empty($statusArray) || (in_array($co_app_is_existing->state, $statusArray)))) {
                $status = true;
                $existing['Co-App Pan Card'] = $co_app_is_existing;
            }
        }
        if ((isset($application->email) && $application->email)) {
            $is_existing = ConsumerApplication::where('id', '!=', $application_id)->where('email', 'like', '%'.trim($application->email).'%');
            $co_app_is_existing = ConsumerApplication::where('id', '!=', $application_id)->where('co_applicant_email', 'like', '%'.trim($application->email).'%');

            if ($statusArray) {
                $is_existing = $is_existing->whereIn('state', $statusArray);
                $co_app_is_existing = $co_app_is_existing->whereIn('state', $statusArray);
            }
            $is_existing = $is_existing->whereNull('is_deleted')->first(['id', 'state', 'name']);
            $co_app_is_existing = $co_app_is_existing->whereNull('is_deleted')->first(['id', 'state', 'name']);
            if (isset($is_existing->id) && (empty($statusArray) || (in_array($is_existing->state, $statusArray)))) {
                $status = true;
                $existing['Email'] = $is_existing;
            }

            if (isset($co_app_is_existing->id) && (empty($statusArray) || (in_array($co_app_is_existing->state, $statusArray)))) {
                $status = true;
                $existing['Co-App Email'] = $co_app_is_existing;
            }
        }
        if ((isset($application->mobile_number) && $application->mobile_number)) {
            $is_existing = ConsumerApplication::where('id', '!=', $application_id)->where('mobile_number', 'like', '%'.trim($application->mobile_number).'%');
            $co_app_is_existing = ConsumerApplication::where('id', '!=', $application_id)->where('co_applicant_mobile_number', 'like', '%'.trim($application->mobile_number).'%');

            if ($statusArray) {
                $is_existing = $is_existing->whereIn('state', $statusArray);
            }
            $is_existing = $is_existing->whereNull('is_deleted')->first(['id', 'state', 'name']);
            $co_app_is_existing = $co_app_is_existing->whereNull('is_deleted')->first(['id', 'state', 'name']);
            if (isset($is_existing->id) && (empty($statusArray) || (in_array($is_existing->state, $statusArray)))) {
                $status = true;
                $existing['Mobile No.'] = $is_existing;
            }
            if (isset($co_app_is_existing->id) && (empty($statusArray) || (in_array($co_app_is_existing->state, $statusArray)))) {
                $status = true;
                $existing['Co-App Mobile No.'] = $co_app_is_existing;
            }
        }
        if ((isset($application->aadhaar_card) && $application->aadhaar_card)) {
            $is_existing = ConsumerApplication::where('id', '!=', $application_id)->where('aadhaar_card', 'like', '%'.trim($application->aadhaar_card).'%');
            $co_app_is_existing = ConsumerApplication::where('id', '!=', $application_id)->where('co_applicant_aadhaar_card', 'like', '%'.trim($application->aadhaar_card).'%');

            if ($statusArray) {
                $is_existing = $is_existing->whereIn('state', $statusArray);
                $co_app_is_existing = $is_existing->whereIn('state', $statusArray);
            }
            $is_existing = $is_existing->whereNull('is_deleted')->first(['id', 'state', 'name']);
            $co_app_is_existing = $co_app_is_existing->whereNull('is_deleted')->first(['id', 'state', 'name']);
            if (isset($is_existing->id) && (empty($statusArray) || (in_array($is_existing->state, $statusArray)))) {
                $status = true;
                $existing['Aadhaar Card'] = $is_existing;
            }
            if (isset($co_app_is_existing->id) && (empty($statusArray) || (in_array($co_app_is_existing->state, $statusArray)))) {
                $status = true;
                $existing['Co-App Aadhaar Card'] = $co_app_is_existing;
            }
        }
        if (isset($application->co_applicant_pan_card) && $application->co_applicant_pan_card) {
            $is_existing = ConsumerApplication::where('id', '!=', $application_id)->where('pan_card', 'like', '%' . trim($application->co_applicant_pan_card) . '%');
            $co_app_is_existing = ConsumerApplication::where('id', '!=', $application_id)->where('co_applicant_pan_card', 'like', '%' . trim($application->co_applicant_pan_card) . '%');

            if ($statusArray) {
                $is_existing = $is_existing->whereIn('state', $statusArray);
                $co_app_is_existing = $co_app_is_existing->whereIn('state', $statusArray);
            }

            $is_existing = $is_existing->whereNull('is_deleted')->first(['id', 'state', 'name']);
            $co_app_is_existing = $co_app_is_existing->whereNull('is_deleted')->first(['id', 'state', 'name']);
            if (isset($is_existing->id) && (empty($statusArray) || (in_array($is_existing->state, $statusArray)))) {
                $status = true;
                $existing['Pan Card'] = $is_existing;
            }

            if (isset($co_app_is_existing->id) && (empty($statusArray) || (in_array($co_app_is_existing->state, $statusArray)))) {
                $status = true;
                $existing['Co-App Pan Card'] = $co_app_is_existing;
            }
        }
        if (isset($application->co_applicant_email) && $application->co_applicant_email) {
            $is_existing = ConsumerApplication::where('id', '!=', $application_id)->where('email', 'like', '%' . trim($application->co_applicant_email) . '%');
            $co_app_is_existing = ConsumerApplication::where('id', '!=', $application_id)->where('co_applicant_email', 'like', '%' . trim($application->co_applicant_email) . '%');


            if ($statusArray) {
                $is_existing = $is_existing->whereIn('state', $statusArray);
                $co_app_is_existing = $co_app_is_existing->whereIn('state', $statusArray);
            }
            $is_existing = $is_existing->whereNull('is_deleted')->first(['id', 'state', 'name']);
            $co_app_is_existing = $co_app_is_existing->whereNull('is_deleted')->first(['id', 'state', 'name']);
            if (isset($is_existing->id) && (empty($statusArray) || (in_array($is_existing->state, $statusArray)))) {
                $status = true;
                $existing['Email'] = $is_existing;
            }

            if (isset($co_app_is_existing->id) && (empty($statusArray) || (in_array($co_app_is_existing->state, $statusArray)))) {
                $status = true;
                $existing['Co-App Email'] = $co_app_is_existing;
            }
        }
        if (isset($application->co_applicant_mobile_number) && $application->co_applicant_mobile_number) {
            $is_existing = ConsumerApplication::where('id', '!=', $application_id)->where('mobile_number', 'like', '%' . trim($application->co_applicant_mobile_number) . '%');
            $co_app_is_existing = ConsumerApplication::where('id', '!=', $application_id)->where('co_applicant_mobile_number', 'like', '%' . trim($application->co_applicant_mobile_number) . '%');


            if ($statusArray) {
                $is_existing = $is_existing->whereIn('state', $statusArray);
            }
            $is_existing = $is_existing->whereNull('is_deleted')->first(['id', 'state', 'name']);
            $co_app_is_existing = $co_app_is_existing->whereNull('is_deleted')->first(['id', 'state', 'name']);
            if (isset($is_existing->id) && (empty($statusArray) || (in_array($is_existing->state, $statusArray)))) {
                $status = true;
                $existing['Mobile No.'] = $is_existing;
            }
            if (isset($co_app_is_existing->id) && (empty($statusArray) || (in_array($co_app_is_existing->state, $statusArray)))) {
                $status = true;
                $existing['Co-App Mobile No.'] = $co_app_is_existing;
            }
        }
        if (isset($application->co_applicant_aadhaar_card) && $application->co_applicant_aadhaar_card) {
            $is_existing = ConsumerApplication::where('id', '!=', $application_id)->where('aadhaar_card', 'like', '%' . trim($application->co_applicant_aadhaar_card) . '%');
            $co_app_is_existing = ConsumerApplication::where('id', '!=', $application_id)->where('co_applicant_aadhaar_card', 'like', '%' . trim($application->co_applicant_aadhaar_card) . '%');


            if ($statusArray) {
                $is_existing = $is_existing->whereIn('state', $statusArray);
                $co_app_is_existing = $is_existing->whereIn('state', $statusArray);
            }
            $is_existing = $is_existing->whereNull('is_deleted')->first(['id', 'state', 'name']);
            $co_app_is_existing = $co_app_is_existing->whereNull('is_deleted')->first(['id', 'state', 'name']);
            if (isset($is_existing->id) && (empty($statusArray) || (in_array($is_existing->state, $statusArray)))) {
                $status = true;
                $existing['Aadhaar Card'] = $is_existing;
            }
            if (isset($co_app_is_existing->id) && (empty($statusArray) || (in_array($co_app_is_existing->state, $statusArray)))) {
                $status = true;
                $existing['Co-App Aadhaar Card'] = $co_app_is_existing;
            }
        }

        $isGood = true;
        $repeat_list = '';
        if ($isProcessingCheck) {
            $isGood = false;
            if ($application->merchant && $application->merchant->is_processing_fees == 1) {
                $isGood = true;
            }
        }

        if ($status && $isGood) {
            if($isProcessingCheck){
                return true;
            }else{
                foreach($existing as $key => $value){
                    $repeat_list .= $value->id . ' - ' . $value->name . ' [' . $key . ']'."\n<br>"; /*Something needs to be added here cna't seem to add a break or preview the text*/
                }
                return $repeat_list;
            }
        }

        return false;
    }

    public function sendAdvanceAmountLink($advance_amount, $application)
    {
        $razorpaydata['amount'] = $advance_amount;
        $razorpaydata['email'] = "";
        $razorpaydata['lender_id'] = $application->lender->id;
        $razorpaydata['id'] = $application->id;
        $razorpaydata['purpose'] = 'advance_amount';
        $razorpaydata['emi_date'] = $application->emi->emi_date;

        $disableAvansePayment = false;

        if ( (1 == _env('AVANSE_PAYMENT_ENABLE')) && !empty($razorpaydata['lender_id'])
            && $razorpaydata['lender_id'] === ConsumerApplication::AVANSE_LENDER_ID && $disableAvansePayment) {
            // check if payment link is already generated
            $opObj = OnlinePayment::where('application_id', $application->id)
                        ->where('purpose', 'advance_amount')
                        ->whereNotNull('payment_link')
                        ->first();
            if (!empty($opObj)) {
                if (strtolower($opObj->status) === 'pending') {
                    return $opObj->payment_link;
                } else {
                    //return '';
                }
            }

            // Payment link not generated, check if application state is approved, only then generate the payment link
            if (!empty($application->state) && $application->state === 'approved') {
                $avlid = AvanseCreateFinance::getAvanseLoanId($application->id);
                if (false !== $avlid) {
                    $razorpaydata['laNumber'] = $avlid;
                    $razorpaydata['id'] = $application->id;
                    $rece = [];
                    $recv[0]['name'] = !empty($application->name) ? $application->name : '';
                    $recv[0]['mobileNumber'] = !empty($application->mobile_number) ? $application->mobile_number : '';
                    $recv[0]['emailId'] = !empty($application->email) ? $application->email : '';
                    $recv[0]['accountName'] = "Applicant";
                    if (!empty($application->co_applicant_mobile_number)) {
                        $recv[1]['name'] = !empty($application->co_applicant_name) ? $application->co_applicant_name : '';
                        $recv[1]['mobileNumber'] = !empty($application->co_applicant_mobile_number) ? $application->co_applicant_mobile_number : '';
                        $recv[1]['emailId'] = !empty($application->co_applicant_email) ? $application->co_applicant_email : '';
                        $recv[1]['accountName'] = "Co-Applicant";
                    }
                    $razorpaydata['receipents'] = $recv;
                    return AvanseProcesses::getPaymentLink($razorpaydata);
                }
            }
            return '';
        } else {
            return $this->getrazorpaylink($razorpaydata);
        }
    }

    public function sendInsuranceFeeLink($insurance_fee_amount, $application)
    {
        $razorpaydata['amount'] = $insurance_fee_amount;
        $razorpaydata['email'] = "";
        $razorpaydata['lender_id'] = $application->lender->id;
        $razorpaydata['id'] = $application->id;
        $razorpaydata['purpose'] = 'insurance_fee';
        $razorpaydata['emi_date'] = $application->emi->emi_date;

        if ((1 == _env('AVANSE_PAYMENT_ENABLE')) && !empty($razorpaydata['lender_id']) && $razorpaydata['lender_id'] === ConsumerApplication::AVANSE_LENDER_ID) {
            return $this->getrazorpaylink($razorpaydata);
            // $avlid = AvanseCreateFinance::getAvanseLoanId($application->id);
            // if (false !== $avlid) {
            //     $razorpaydata['laNumber'] = $avlid;
            //     $rece = [];
            //     $recv[0]['name'] = !empty($application->name) ? $application->name : '';
            //     $recv[0]['mobileNumber'] = !empty($application->mobile_number) ? $application->mobile_number : '';
            //     $recv[0]['emailId'] = !empty($application->email) ? $application->email : '';
            //     $recv[0]['accountName'] = "Applicant";
            //     if (!empty($application->co_applicant_mobile_number)) {
            //         $recv[1]['name'] = !empty($application->co_applicant_name) ? $application->co_applicant_name : '';
            //         $recv[1]['mobileNumber'] = !empty($application->co_applicant_mobile_number) ? $application->co_applicant_mobile_number : '';
            //         $recv[1]['emailId'] = !empty($application->co_applicant_email) ? $application->co_applicant_email : '';
            //         $recv[1]['accountName'] = "Co-Applicant";
            //     }
            //     $razorpaydata['receipents'] = $recv;
            //     return AvanseProcesses::getPaymentLink($razorpaydata);
            // }
            // return '';
        } else {
            return $this->getrazorpaylink($razorpaydata);
        }
    }
    public function sendLegalChargesLink($legalCharges, $application)
    {
        $razorpaydata['amount'] = $legalCharges;
        $razorpaydata['email'] = "";
        $razorpaydata['lender_id'] = $application->lender_id;
        $razorpaydata['id'] = $application->id;
        $razorpaydata['purpose'] = 'legal_charges';
        $razorpaydata['emi_date'] = $application->emi->emi_date;

        if ((1 == _env('AVANSE_PAYMENT_ENABLE')) && !empty($razorpaydata['lender_id']) && $razorpaydata['lender_id'] === ConsumerApplication::AVANSE_LENDER_ID) {
            return $this->getrazorpaylink($razorpaydata);
            // $avlid = AvanseCreateFinance::getAvanseLoanId($application->id);
            // if (false !== $avlid) {
            //     $razorpaydata['laNumber'] = $avlid;
            //     $rece = [];
            //     $recv[0]['name'] = !empty($application->name) ? $application->name : '';
            //     $recv[0]['mobileNumber'] = !empty($application->mobile_number) ? $application->mobile_number : '';
            //     $recv[0]['emailId'] = !empty($application->email) ? $application->email : '';
            //     $recv[0]['accountName'] = "Applicant";
            //     if (!empty($application->co_applicant_mobile_number)) {
            //         $recv[1]['name'] = !empty($application->co_applicant_name) ? $application->co_applicant_name : '';
            //         $recv[1]['mobileNumber'] = !empty($application->co_applicant_mobile_number) ? $application->co_applicant_mobile_number : '';
            //         $recv[1]['emailId'] = !empty($application->co_applicant_email) ? $application->co_applicant_email : '';
            //         $recv[1]['accountName'] = "Co-Applicant";
            //     }
            //     $razorpaydata['receipents'] = $recv;
            //     return AvanseProcesses::getPaymentLink($razorpaydata);
            // }
            // return '';
        } else {
            return $this->getrazorpaylink($razorpaydata);
        }
    }

    public function sendProcessingFeeLink($data, $application)
    {
        // if ($data['pending_amount'] > 0) {
        //     $razorpaydata['amount'] = $data['pending_amount'];
        //     // TODO: cloudwatch log to be added
        // }
        if (isset($data['pending_amount']) && $data['pending_amount'] > 0){
            $razorpaydata['amount'] = $data['pending_amount'];
        }
        else {
            $razorpaydata['amount'] = $data['consumer_emi']->processing_fee;
        }
        $razorpaydata['email'] = "";
        $razorpaydata['lender_id'] = $application->lender->id;
        $razorpaydata['id'] = $application->id;
        $razorpaydata['purpose'] = 'processing_fee';
        $razorpaydata['emi_date'] = $application->emi->emi_date;

        // Payment link returned since condition doesnt match for avanse cases post API calling changes.
        return $this->getrazorpaylink($razorpaydata);

        if ((1 == _env('AVANSE_PAYMENT_ENABLE')) && !empty($razorpaydata['lender_id']) && $razorpaydata['lender_id'] === ConsumerApplication::AVANSE_LENDER_ID) {
            // check if payment link is already generated
            $opObj = OnlinePayment::where('application_id', $application->id)
                        ->where('purpose', 'processing_fee')
                        ->whereNotNull('payment_link')
                        ->first();
            if (!empty($opObj)) {
                if (strtolower($opObj->status) === 'pending') {
                    return $opObj->payment_link;
                } else {
                    //return '';
                }
            }

            // Payment link not generated, check if application state is approved, only then generate the payment link
            if (!empty($application->state) && $application->state === 'approved') {
                $avlid = AvanseCreateFinance::getAvanseLoanId($application->id);
                if (false !== $avlid) {
                    $razorpaydata['laNumber'] = $avlid;
                    $razorpaydata['id'] = $application->id;
                    $rece = [];
                    $recv[0]['name'] = !empty($application->name) ? $application->name : '';
                    $recv[0]['mobileNumber'] = !empty($application->mobile_number) ? $application->mobile_number : '';
                    $recv[0]['emailId'] = !empty($application->email) ? $application->email : '';
                    $recv[0]['accountName'] = "Applicant";
                    $razorpaydata['receipents'] = $recv;
                    return AvanseProcesses::getPaymentLink($razorpaydata);
                }
            }
            return '';
        } else {
            return $this->getrazorpaylink($razorpaydata);
        }

//        $payment = OnlinePayment::where('application_id', $application_id)
//        ->where('purpose','processing_fee')->where('emi_date',$razorpaydata['emi_date'])
//        ->where('amount',$razorpaydata['amount'])->first(['id','payment_link']);
//        $customAmount = $data['consumer_emi']->processing_fee;
//        $amount_processing_fees = $customAmount .'|'.'0'.'|processing_fee';
//        $amount_processng_fees_encrypter = base64_encode(wall_encrypt($amount_processing_fees));
//
//        $hashids = new Hashids('Creditfair by CS', 20);
//        $hashed_id = $hashids->encode($application_id);
//
//        $payment_link = (asset("paytm/" . $hashed_id . "?data=" . $amount_processng_fees_encrypter));
//  
//        try {
//            $payment_link = \Bitly::getUrl($payment_link);
//        }catch (\Exception $e){
//        }
        //return $payment_link;
        //return isset($payment->id) ? $payment->payment_link : $this->getrazorpaylink($razorpaydata);
    }

    public function sendTotalPaymentLink($totalAmount, $application) {
        try {
            if(isset($application->lender->id) && isset($application->emi->emi_date)) {
                $razorpaydata['amount'] = $totalAmount;
                $razorpaydata['email'] = $application->email;
                $razorpaydata['lender_id'] = $application->lender->id;
                $razorpaydata['id'] = $application->id;
                $razorpaydata['purpose'] = 'total_fee';
                $razorpaydata['emi_date'] = $application->emi->emi_date;
                return $this->getrazorpaylink($razorpaydata);
            }
        } catch (Exception $e){
            $cwFactory = new CloudWatchLoggerFactory();
            $data = array('title' => 'Total Payment Error', 'application_id' => $application->id ?? '', 'message' => $e->getMessage(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString());
            $cwFactory->logger(json_encode($data));
        }
    }

    public function getLoanAgreemenNumber($application_id, $application = null){

        $type = 7;
        $concatstring = "";
        if (!$application){
            $application = ConsumerApplication::with('merchant')->where('id', $application_id)->first(['id', 'merchant_id']);
        }

        if($application->merchant_id == 5026){
            $type = 8;
        }

        if (strlen($application_id) < $type) {
            $diff = $type - strlen($application_id);
            for ($i = 0; $i < $diff; $i++) {
                $concatstring = $concatstring . "0";
            }
        }
        return $application->merchant->slug . $concatstring . $application_id;
    }

    public function updateProforma($application_id)
    {
        $proforma = ProFormaInvoice::where('application_id', $application_id)->first();
        $application = ConsumerApplication::with('merchant', 'merchant_location')->where('id', $application_id)->first();
        $merchantInsuranceConfig = (new AccountingController())->getMerchantInsuranceConfig($application_id);
        if (!isset($proforma->id)) {
            if (!isset($application->merchant) && is_null($application->merchant)) {
                return ;
            }
            $gstnumber = "";
            if (isset($application->merchant_location->gst_number) && $application->merchant_location->gst_number != "" && $application->merchant_location->gst_number != 0) {
                $gstnumber = $application->merchant_location->gst_number;
            } elseif (isset($application->merchant->gst_number) && $application->merchant->gst_number != "" && $application->merchant->gst_number != 0) {
                $gstnumber = $application->merchant->gst_number;
            }
            $concatstring = "";
            $type = 7;

            if($application->merchant_id == 5026){
                $type = 8;
            }

            if (strlen($application_id) < $type) {
                $diff = $type - strlen($application_id);
                for ($i = 0; $i < $diff; $i++) {
                    $concatstring = $concatstring . "0";
                }
            }
            $loan_application_id = $application->merchant->slug . $concatstring . $application_id;

            $proforma = new ProFormaInvoice();
            $proforma->application_id = $application_id;
            $proforma->gst_number = $gstnumber;
            $proforma->center_name = isset($application->merchant_location->name) ? $application->merchant_location->name : '';
            $proforma->merchant_collected_advance_amount = isset($application->merchant->collect_advance_amount) ? $application->merchant->collect_advance_amount : 0;
            $proforma->insurance_premium_by_merchant = $merchantInsuranceConfig['insurance_premium_by_merchant'];
            $proforma->insurance_premium_applicable = $merchantInsuranceConfig['insurance_premium_applicable'];
            $proforma->insurance_coverage = $merchantInsuranceConfig['insurance_coverage'];
            $proforma->customer_name = $application->name;
            $proforma->loan_application_no = $loan_application_id;
            $proforma->processing_fee_by_merchant = $application->merchant->is_collected;
            $proforma->save();
        }else{
            ProFormaInvoice::where('id', $proforma->id)->update([
                'processing_fee_by_merchant' => isset($proforma->processing_fee_by_merchant) ? $proforma->processing_fee_by_merchant : $application->merchant->is_collected,
                'merchant_collected_advance_amount' => isset($application->merchant->collect_advance_amount) ? $application->merchant->collect_advance_amount : 0,
                'insurance_premium_by_merchant' => $merchantInsuranceConfig['insurance_premium_by_merchant'],
                'insurance_premium_applicable' => $merchantInsuranceConfig['insurance_premium_applicable'],
                'insurance_coverage' => $merchantInsuranceConfig['insurance_coverage']
            ]);
        }
    }

    public function InvokeCommunicationPayout($id, $retry = 0, $setPhase = false){
        $JobProvider = JobProvider::where('application_id', $id)->where('from','InvokeCommunicationPayout')->first(['id']);
        if(!isset($JobProvider->id)) {
            $payload[] = [
                'payload' => json_encode(['application_id' => $id, 'retry' => $retry, 'setPhase'=>$setPhase]),
                'from' => 'InvokeCommunicationPayout',
                'application_id' => $id,
                'available_at' => Carbon::now()->addMinute(60)->toDateTimeString(),
                'created_at' => Carbon::now()->toDateTimeString()
            ];

            JobProvider::insert($payload);
        }else{
            $payload = json_encode(['application_id' => $id, 'retry' => $retry, 'setPhase'=>$setPhase]);
            JobProvider::where('id', $JobProvider->id)->update(['available_at' => Carbon::now()->addMinute(60)->toDateTimeString(), 'is_available' => 0, 'payload' => $payload]);
        }
    }

    public function getDisbursementAmount($id){

        $application = $documentDetails = ConsumerApplication::with('emi', 'proFormaInvoice', 'offer', 'merchant')->where('id', $id)->first(['id', 'merchant_id','name', 'offer_id']);

        $documentDetails['netdisbusedamount'] = $documentDetails['emi']['upfront_from_credit_fair'] - ($documentDetails['emi']['subvention_igst'] + $documentDetails['emi']['subvention_cgst'] + $documentDetails['emi']['subvention_sgst']);

        $merchant_processing_collected = isset($documentDetails['merchant']->is_collected) && $documentDetails['merchant']->is_collected == 1 ? $documentDetails['merchant']->is_collected : (isset($documentDetails['proFormaInvoice']) && $documentDetails['proFormaInvoice']->processing_fee_by_merchant == 1 ? $documentDetails['proFormaInvoice']->processing_fee_by_merchant : 0);

        $disbursement_phase = false;
        if((new MultiStageDisbursement())->canPartialDisbursement($application->emi->offer_id, $application)) {
            $disbursement_phase = MultiStageDisbursement::isPartialDisbursement($application);
        }
        $disbursement_phase = is_bool($disbursement_phase) ? $disbursement_phase : count($disbursement_phase);


        if($merchant_processing_collected == 1 && (!$disbursement_phase)){
            if((!isset($user['offer']->processing_fee_first_emi) || (isset($user['offer']->processing_fee_first_emi) && !$user['offer']->processing_fee_first_emi))){
                $documentDetails['netdisbusedamount'] = $documentDetails['netdisbusedamount'] - $documentDetails['emi']['processing_fee'];
            }
        }

        /*if (isset($documentDetails['proFormaInvoice']['processing_fee_by_merchant']) && $documentDetails['proFormaInvoice']['processing_fee_by_merchant'] == 1) {
            $documentDetails['netdisbusedamount'] = $documentDetails['netdisbusedamount'] - $documentDetails['emi']['processing_fee'];
        }

        $merchant_processing_collected = isset($documentDetails->merchant->is_collected) && $documentDetails->merchant->is_collected == 1 ? $documentDetails->merchant->is_collected : (isset($documentDetails->proFormaInvoice) && $documentDetails->proFormaInvoice->processing_fee_by_merchant == 1 ? $documentDetails->proFormaInvoice->processing_fee_by_merchant : 0);
        if($merchant_processing_collected == 1) {
            if ((!isset($user['activeOffer']->processing_fee_first_emi) || (isset($user['activeOffer']->processing_fee_first_emi) && !$user['activeOffer']->processing_fee_first_emi))) {
                $documentDetails['netdisbusedamount'] = $documentDetails['netdisbusedamount'] - $documentDetails['emi']['processing_fee'];
            }
        }*/

        $insurance_premium_amount = isset($documentDetails['proFormaInvoice']->insurance_premium_amount) && $documentDetails['proFormaInvoice']->insurance_premium_applicable == 1 && $documentDetails['proFormaInvoice']->insurance_premium_by_merchant == 1 ? $documentDetails['proFormaInvoice']->insurance_premium_amount : 0;
        if($insurance_premium_amount && (!isset($documentDetails['disbursement_phase']) || (isset($documentDetails['disbursement_phase']) && $insurance_premium_amount && ($documentDetails['phase_cycle']) == 1))){
            $documentDetails['netdisbusedamount'] = $documentDetails['netdisbusedamount'] - $insurance_premium_amount;
        }


        if(isset($documentDetails['user']['consumer_emi']['legal_charges']) && $merchant_processing_collected == 1){
            $documentDetails['netdisbusedamount'] = $documentDetails['netdisbusedamount'] - $documentDetails['user']['consumer_emi']['legal_charges'];
        }

        $upfront_from_customer = isset($documentDetails['proFormaInvoice']->merchant_collected_advance_amount) && $documentDetails['proFormaInvoice']->merchant_collected_advance_amount == 1 ? $documentDetails['emi']['upfront_from_customer'] : 0;
        if($upfront_from_customer){
            $documentDetails['netdisbusedamount'] = $documentDetails['netdisbusedamount'] + $upfront_from_customer;
        }

        $disbursementAmount = Disbursement::where('application_id', $id)->where('is_cancellation_adjusted', 1)->first(['id', 'disbursed', 'upfront_from_credit_fair', 'adjusted_against', 'emi_adjusted']);

        $doNotSubWithHeldAmount = false;
        if (isset($documentDetails['disbursement_amount']) && $documentDetails['disbursement_amount'] > 0) {
            /**End MultiStage Disbursements**/
            $documentDetails['netdisbusedamount'] = $documentDetails['disbursement_amount'];
            /**End MultiStage Disbursements**/

        } else if (isset($disbursementAmount->id)) {
            /**Cancellation Disbursements**/
            $documentDetails['netdisbusedamount'] = $disbursementAmount->disbursed;
            $doNotSubWithHeldAmount = true;
        }

        if(!$disbursement_phase && !$doNotSubWithHeldAmount){
            $withheld_percent = LiabilityLog::where('application_id', $id)->orderBy('created_at', 'desc')->first(['liability_amount']);
            $withheld_amount = isset($withheld_percent->liability_amount) ? $withheld_percent->liability_amount : 0;
            $documentDetails['netdisbusedamount'] = $documentDetails['netdisbusedamount'] - $withheld_amount;
        }


        return $documentDetails['netdisbusedamount'];
    }

    public function invokeCommunication($application_id, $isRoot = false, $payload = [])
    {
        $request = new Request();
        $request->request->add([
            'type' => 'Merchant Disbursed',
            'bot' => true,
            'from_mail' => env('CENTRALOPS')
        ]);
        $document = (new ConsumerDocument($request));
        $documentDetails = $document->getDocument($application_id);
        $isGSTAvaliable = false;
        // (new Slack(new Request(['title' => 'Multistage error logs9', 'fields' => ['application_id' => $application_id]])))->send();
        $documentDetails['netdisbusedamount'] = $documentDetails['user']['consumer_emi']['upfront_from_credit_fair'] - ($documentDetails['user']['consumer_emi']['subvention_igst'] + $documentDetails['user']['consumer_emi']['subvention_cgst'] + $documentDetails['user']['consumer_emi']['subvention_sgst']);
        if (isset($documentDetails['user']['proFormaInvoice']['processing_fee_by_merchant']) && $documentDetails['user']['proFormaInvoice']['processing_fee_by_merchant'] == 1) {
            $documentDetails['netdisbusedamount'] = $documentDetails['netdisbusedamount'] - $documentDetails['user']['consumer_emi']['processing_fee'];
            $documentDetails['netdisbusedamount'] = $documentDetails['netdisbusedamount'] - $documentDetails['user']['consumer_emi']['legal_charges'];
        }

        $insurance_premium_amount = isset($documentDetails['user']['proFormaInvoice']->insurance_premium_amount) && $documentDetails['user']['proFormaInvoice']->insurance_premium_applicable == 1 && $documentDetails['user']['proFormaInvoice']->insurance_premium_by_merchant == 1 ? $documentDetails['user']['proFormaInvoice']->insurance_premium_amount : 0;
        if($insurance_premium_amount && (!isset($documentDetails['user']['disbursement_phase']) || (isset($documentDetails['user']['disbursement_phase']) && $insurance_premium_amount && ($documentDetails['user']['phase_cycle']) == 1))){
            $documentDetails['netdisbusedamount'] = $documentDetails['netdisbusedamount'] - $insurance_premium_amount;
        }

        $upfront_from_customer = isset($documentDetails['user']['proFormaInvoice']->merchant_collected_advance_amount) && $documentDetails['user']['proFormaInvoice']->merchant_collected_advance_amount == 1 ? $documentDetails['user']['consumer_emi']['upfront_from_customer'] : 0;
        if($upfront_from_customer){
            $documentDetails['netdisbusedamount'] = $documentDetails['netdisbusedamount'] + $upfront_from_customer;
        }

        if (isset($documentDetails['user']['getGSTDetailsSubvention']) && !empty($documentDetails['user']['getGSTDetailsSubvention']) && $documentDetails['user']['getGSTDetailsSubvention'] > 0) {
            $isGSTAvaliable = true;
        }

        $applicationElement = ConsumerApplicationElement::where('application_id', $application_id)->where('is_payout', 1)->first(['id']);

        if (isset($documentDetails['user']['purpose_of_the_loan']) && ($documentDetails['user']['purpose_of_the_loan'] != 'Personal Loan' || ($documentDetails['user']['purpose_of_the_loan'] == 'Personal Loan' && isset($applicationElement->id)))) {
            if($documentDetails['user']['merchant_id'] != 21) {
                if (isset($documentDetails['user']['center_gst_number']) && !empty($documentDetails['user']['center_gst_number'])) {
                    $bank_name = isset($documentDetails['user']['center_bank']['bank_name']) ? $documentDetails['user']['center_bank']['bank_name'] : "";
                    $account_number = isset($documentDetails['user']['center_bank']['account_number']) ? (str_repeat('X', strlen(substr($documentDetails['user']['center_bank']['account_number'], 0, -4))) . substr($documentDetails['user']['center_bank']['account_number'], -4)) : "";
                } else {
                    $bank_name = isset($documentDetails['user']['merchant_bank_details']['bank_name']) ? $documentDetails['user']['merchant_bank_details']['bank_name'] : "";
                    $account_number = isset($documentDetails['user']['merchant_bank_details']['account_number']) ? (str_repeat('X', strlen(substr($documentDetails['user']['merchant_bank_details']['account_number'], 0, -4))) . substr($documentDetails['user']['merchant_bank_details']['account_number'], -4)) : "";
                }
            }else{
                $bankDisbursal = Bank::where('application_id', $application_id)->first(['account_number','ifsc_code','name as account_holder','karza_response']);
                if(isset($bankDisbursal->account_holder) && $bankDisbursal->account_holder){
                    $bank_name = $bankDisbursal->account_holder;
                    $account_number = $bankDisbursal->account_number;
                }
            }

            $isAdjustment = false;
            $isCancellationAdjustment = '';
            $disbursementAmount = Disbursement::where('application_id', $application_id)->where('is_cancellation_adjusted', 1)->first(['id', 'disbursed', 'upfront_from_credit_fair', 'adjusted_against', 'emi_adjusted']);

            if (isset($documentDetails['user']['disbursement_amount']) && $documentDetails['user']['disbursement_amount'] > 0) {
                /**End MultiStage Disbursements**/
                $documentDetails['netdisbusedamount'] = $documentDetails['user']['disbursement_amount'];
                /**End MultiStage Disbursements**/

            } else if (isset($disbursementAmount->id)) {
                /**Cancellation Disbursements**/
                $documentDetails['netdisbusedamount'] = $disbursementAmount->disbursed;
                $documentDetails['to_be_disbursed'] = $disbursementAmount->upfront_from_credit_fair;

                if (isset($disbursementAmount->adjusted_against) && !empty($disbursementAmount->adjusted_against)) {
                    $documentDetails['cancellationDisbursement'] = CancellationDisbursement::with('application')->whereIn('id', json_decode($disbursementAmount->adjusted_against))->get();
                }

                if (isset($disbursementAmount->emi_adjusted) && !empty($disbursementAmount->emi_adjusted)) {
                    $emi_adjusted = json_decode($disbursementAmount->emi_adjusted);
                    if ($emi_adjusted) {
                        $paymentTransactionAdjust = PaymentTransaction::with('application')->whereIn('id', $emi_adjusted)->get(['id', 'application_id', 'amount as total_amount_adjusted']);
                        if (isset($documentDetails['cancellationDisbursement']) && $documentDetails['cancellationDisbursement']) {
                            $documentDetails['cancellationDisbursement'] = $documentDetails['cancellationDisbursement']->merge($paymentTransactionAdjust);
                        } else {
                            $documentDetails['cancellationDisbursement'] = $paymentTransactionAdjust;
                        }

                        $isCancellationAdjustment = 'Adjustments have been made for this disbursement.<br/>';
                    }
                }

                /**End Cancellation Disbursements**/
                $isAdjustment = true;
            }

            $withHoldMessage = '';
            if(isset($documentDetails['user']['withhold']) && $documentDetails['user']['withhold'] > 0){
                $withHoldMessage = $documentDetails['user']['withhold'];
            }


            if(isset($documentDetails['lender']) && isset($documentDetails['lender']->id) && in_array($documentDetails['lender']->id, [2, 20])) {
                $this->tradeAdvanceDisbursement($application_id, $documentDetails);
            }
            /*PayTM Payout*/
            // (new Slack(new Request(['title' => 'Multistage error logs10', 'fields' => ['application_id' => $application_id]])))->send();
            if(isset($applicationElement->id)){
                if(_env('payout') == 'paytm') {
                    $payoutStatus = PayoutStatus::where('application_id', $application_id)->first();
                }else{
                    $paymentStatusTransferCheckPhase = 0;
                    if(isset($documentDetails['user']['disbursement_phase']) && $documentDetails['user']['disbursement_phase']){
                        if(isset($payload->setPhase) && $payload->setPhase){
                            $phase = $documentDetails['user']['phase_cycle']-1;
                        }else{
                            $phase = $documentDetails['user']['phase_cycle'];
                        }
                        $payoutStatusData = CFPayoutDirectTransfer::where('application_id', $application_id)->orderBy('created_at','desc')->where('phase',$phase)->first();
                        // (new Slack(new Request(['title' => 'Multistage error logs11', 'fields' => ['application_id' => $application_id]])))->send();
                        $paymentStatusTransferCheckPhase = $phase;
                    }else{
                        $payoutStatusData = CFPayoutDirectTransfer::where('application_id', $application_id)->orderBy('created_at','desc')->where('phase',0)->first();
                    }
                    if (isset($payoutStatusData->id)){
                        $payoutStatus = new \stdClass();
                        $payoutStatus->id = $payoutStatusData->id;
                        $payoutStatus->referenceId = $payoutStatusData->referenceId;
                        $payoutStatus->status = $payoutStatusData->acknowledged == 1 ? 'SUCCESS' : ($payoutStatusData->acknowledged == 0 ? 'PENDING' : 'FAILURE');
                    }else{
                        $payoutStatus = PayoutStatus::where('application_id', $application_id)->first();
                    }
                }
                if(!isset($payoutStatus->id) || (isset($payload->retry) && $payload->retry)) {
                    $applicationMerchantDetails = ConsumerApplication::with('application_element','application_element.merchant_center','merchant')->where('id', $application_id)->first(['id', 'name','merchant_id']);
                    if (isset($applicationMerchantDetails->merchant_id)) {
                        $merchantBank = $this->getBankAccountDetails($applicationMerchantDetails);
                        if($merchantBank) {
                            //$merchantBank = MerchantBank::where('merchant_id', $applicationMerchantDetails->merchant_id)->first(['account_number as beneficiaryAccount', 'ifsc_code as beneficiaryIFSC']);

                            if(_env('payout') == 'paytm') {
                                $payout = new PayoutAPI(new Request(['id' => $application_id, 'amount' => $documentDetails['netdisbusedamount'], 'beneficiaryAccount' => $merchantBank['beneficiaryAccount'], 'beneficiaryIFSC' => $merchantBank['beneficiaryIFSC'], 'beneficiaryName' => $merchantBank['beneficiaryName']]));
                                $payout->prepare()->initiateDisbursement();
                            }else{
                                // to stop same application id to be passed to cashfree for multi-tranche
                                if(isset($documentDetails['user']['phase_cycle'])){
                                    $transferId = $application_id.'_'.($documentDetails['user']['phase_cycle']);
                                }else{
                                    $transferId = $application_id;
                                }
                                $payout = new PayoutCFAPI(new Request(['id' => $application_id, 'amount' => round($documentDetails['netdisbusedamount'], 2), 'bankAccount' => $merchantBank['beneficiaryAccount'], 'ifsc' => $merchantBank['beneficiaryIFSC'], 'name' => $merchantBank['beneficiaryName'], 'transferId' => $transferId, 'phase' => $documentDetails['user']['phase_cycle'] ?? 0, 'address1' => $applicationMerchantDetails->merchant->address, 'email' => explode(',', $applicationMerchantDetails->merchant->email)[0] ?? $applicationMerchantDetails->merchant->email, 'phone' => explode(',', $applicationMerchantDetails->merchant->contact_number)[0] ?? $applicationMerchantDetails->merchant->contact_number, 'remarks' => $application_id.' '.$applicationMerchantDetails->merchant_id.' '.preg_replace('/[^A-Za-z0-9\-]/', '', $applicationMerchantDetails->name)]));
                                $checkResult = $this->checkForDoubleDisbursement($documentDetails['user']['phase_cycle'] ?? 0, $application_id);
                                if (!$checkResult) {
                                    return true;
                                }
                                $payoutResponse = $payout->directTransfer();
                                $this->checkTransferStatus($application_id,$documentDetails, $payoutResponse);
                            }
                            $this->InvokeCommunicationPayout($application_id,0,true);
                        }
                        return true;
                    }
                }elseif(!in_array($payoutStatus->status,['SUCCESS','FAILURE'])){
                    if(_env('payout') == 'paytm') {
                        $payout = new PayoutAPI(new Request(['id' => $application_id]));
                        $payoutResponseData = $payout->getDisbursementStatus($application_id);
                    }else{
                        if(isset($documentDetails['user']['phase_cycle'])){
                            if(isset($payload->setPhase) && $payload->setPhase){
                                $phase = $documentDetails['user']['phase_cycle']-1;
                            }else{
                                $phase = $documentDetails['user']['phase_cycle'];
                            }
                            $transferId = $application_id.'_'.($phase);
                        }else{
                            $transferId = $application_id;
                        }
                        $payout = new PayoutCFAPI(new Request(['id' => $application_id, 'transferId' => $transferId, 'referenceId' => $payoutStatus->referenceId, 'phase' => $phase ?? 0]));
                        $payoutResponseData = $payout->getTransferStatus();
                    }
                    if($payoutResponseData['response'] && isset($payoutResponseData['response']->status) && $payoutResponseData['response']->status == 'SUCCESS'){

                    }else if(!in_array($payoutResponseData['response']->status, ['FAILURE', 'FAILED'])){
                        $this->InvokeCommunicationPayout($application_id,0,true);
                        return true;
                    }elseif($payoutResponseData['response']->status == 'FAILURE'){
                        return true;
                    }
                }elseif($payoutStatus->status == 'FAILURE' && !Input::has('send-failed-access')){
                    return true;
                }
            }
            /*END*/
            if(isset($payload->setPhase) && $payload->setPhase){
                if(isset($documentDetails['user']['next_phase'])){
                    if($documentDetails['user']['next_phase'] == 2){
                        $_jobs = JobProvider::where('from', 'secondPhaseCommunication')->where('application_id',$application_id)->first(['id']);
                        if(!isset($_jobs->id)) {
                            $payload = [
                                'payload' => json_encode(['id' => $application_id, 'amount' => $documentDetails['netdisbusedamount'], 'account' => $account_number]),
                                'from' => 'secondPhaseCommunication',
                                'application_id' => $application_id,
                                'available_at' => Carbon::now()->toDateTimeString(),
                                'created_at' => Carbon::now()->toDateTimeString()
                            ];
                            JobProvider::insert($payload);
                        }
                    }
                }
            }
            $applicationRow = ConsumerApplication::with('merchant')->where('id', $application_id)->first(['id', 'name','merchant_id']);
            if (!in_array($applicationRow->merchant_id, explode(',', _env('NO_COMM_MERCHANT')))) {
                if($isAdjustment) {
                    $blade = 'merchant_disbursement_adjustment_reminder';
                    $message = str_replace('<br/>', "\n", 'Dear ' . $documentDetails['user']['merchant_name'] . ',<br/>A payment of Rs ' . money_format('%!i', $documentDetails['netdisbusedamount']) . ' on behalf of ' . $documentDetails['user']['customer_name'] . ' has been sent to your ' . $bank_name . ' account ending in ' . $account_number . '. <br/>'.$isCancellationAdjustment.'Now, you can proceed with the delivery of your product/ service to ' . $documentDetails['user']['customer_name'] . '<br/>Regards,<br/>Team Credit Fair,<br/>+919967235047');
                }else{
                    $blade = 'merchant_disbursement_reminder';
                    $message = str_replace('<br/>', "\n", 'Dear ' . $documentDetails['user']['merchant_name'] . ',<br/>A payment of Rs ' . money_format('%!i', $documentDetails['netdisbusedamount']) . ' on behalf of ' . $documentDetails['user']['customer_name'] . ' has been sent to your ' . $bank_name . ' account ending in ' . $account_number . '. <br/>'.$isCancellationAdjustment.'Now, you can proceed with the delivery of your product/ service to ' . $documentDetails['user']['customer_name'] . '<br/>Regards,<br/>Team Credit Fair,<br/>+919967235047');
                }
                if ($withHoldMessage){
                    $blade = 'merchant_disbursement_adjustment_withhold_reminder';
                    $message = str_replace('<br/>', "\n", 'Dear '.$documentDetails['user']['merchant_name'].',<br/><br/>A payment of Rs '.money_format('%!i', $documentDetails['netdisbusedamount']).' on behalf of ' . $documentDetails['user']['customer_name'] . ' has been sent to your '.$bank_name.' account ending in '.$account_number.'.  Rs '.$withHoldMessage.' has been withheld and will be paid to you on successful closure of '. $documentDetails['user']['customer_name'].'’s loan.<br/>'.$isCancellationAdjustment.'Now, you can proceed with the delivery of your product/ service.<br/>Regards,<br/>Team Credit Fair<br/>+91-9967235047');
                }

                if ($isAdjustment) {

                    $data = [
                        'txt' => ($isGSTAvaliable) ? view('admin.documents.subvention_fee_invoice', $documentDetails) : '',
                        'body' => view('emails.reminders.'.$blade, $documentDetails),
                        'subject' => 'Loan Amount Disbursed for ' . $documentDetails['user']['customer_name'],
                        'sms' => $message,
                        'templateId' => '',
                        'args' => ''
                    ];
                } else {
                    $data = [
                        'txt' => ($isGSTAvaliable) ? view('admin.documents.subvention_fee_invoice', $documentDetails) : '',
                        'body' => view('emails.reminders.'.$blade, $documentDetails),
                        'subject' => 'Loan Amount Disbursed for ' . $documentDetails['user']['customer_name'],
                        'sms' => $message,
                        'templateId' => Templates::$disbursed_merchant,
                        'args' => [$documentDetails['user']['merchant_name'], money_format('%!i', $documentDetails['netdisbusedamount']), $documentDetails['user']['customer_name'], $bank_name, $account_number, $documentDetails['user']['customer_name']]
                    ];
                }

                if (isset($documentDetails['user']['disbursement_phase'])) {
                    $ends = array('th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th');
                    $phase = ($documentDetails['user']['phase_cycle']);
                    if (($phase % 100) >= 11 && ($phase % 100) <= 13) {
                        $_ends = $phase . 'th';
                    } else {
                        $_ends = $phase . $ends[$phase % 10];
                    }
                    $data['sms'] = "Dear " . $documentDetails['user']['merchant_name'] . ",<br> The " . $_ends . " phase of disbursement on behalf of "
                        . $documentDetails['user']['customer_name'] . " amounting to Rs.". money_format('%!i', $documentDetails['netdisbusedamount']) . " 
                        has been sent to your account ending in ". $account_number . ". Now you can proceed with the delivery of your product / service.";

                    $data['templateId'] = Templates::$disbursement_phase_c2;
                    $data['args'] = [$documentDetails['user']['merchant_name'], $_ends, $documentDetails['user']['customer_name'], money_format('%!i', $documentDetails['netdisbusedamount']), $account_number];

                    $data['properties'] = $documentDetails['user'];
                }
            }

            if((isset($documentDetails['user']['merchant_id']) && in_array($documentDetails['user']['merchant_id'], [4696, 4829, 4966]))){
                return true;
            }
            $request->request->add($data);
            if ($isRoot) {
                $this->uploadToS3($document, $request, $application_id);
            } else {
                $document->downloadDocument($application_id);
            }

            $this->disbursementAnalysis($application_id);
        }

        if(Input::has('send-failed-access')){
            return \redirect()->to('/admin');
        }
    }

    public function checkForDoubleDisbursement($phase, $application_id){
        $application = DB::selectOne('SELECT offer_id FROM emi_calculation WHERE application_id = '.$application_id);
        $offer = DB::selectOne("select count(id) as phase_count from disbursement_offers where offer_id = ".$application->offer_id);
        (new Slack(new Request(['title' => 'Multi Stage Disbursement', 'fields' => ['application_id' => $application_id, 'phase' => $phase, 'offer phase count' => $offer->phase_count]])))->send();
        if (isset($phase) && isset($offer) && isset($offer->phase_count) && $phase > $offer->phase_count) {
            (new Slack(new Request(['title' => 'Multi Stage Disbursement', 'fields' => ['application_id' => $application_id, 'message' => 'Phase count is not matching']])))->send();
            return false;
        }
        return true;
    }

    public function checkTransferStatus($application_id,$documentDetails, $payoutStatusData){
        /*if(isset($documentDetails['user']['disbursement_phase']) && $documentDetails['user']['disbursement_phase']){
            $payoutStatusData = CFPayoutDirectTransfer::where('application_id', $application_id)->orderBy('created_at','desc')->where('phase',$paymentStatusTransferCheckPhase)->first();
        }else{
            $payoutStatusData = CFPayoutDirectTransfer::where('application_id', $application_id)->orderBy('created_at','desc')->where('phase',0)->first();
        }*/
        //(new Slack(new Request(['title' => 'Check transfer status', 'fields' => ['s' => json_encode($documentDetails['user']['disbursement_phase'] ?? 'No Data'), 'pp' => json_encode($paymentStatusTransferCheckPhase), 'application_id' => $application_id, 'payoutdetails' => json_encode($payoutStatusData)]])))->send();
        if (isset($payoutStatusData->data->referenceId)){
            $payoutStatus = new \stdClass();
            // $payoutStatus->id = $payoutStatusData->id;
            $payoutStatus->referenceId = $payoutStatusData->data->referenceId;
            $payoutStatus->status = $payoutStatusData->data->acknowledged == 1 ? 'SUCCESS' : ($payoutStatusData->data->acknowledged == 0 ? 'PENDING' : 'FAILURE');
        }else{
            $payoutStatus = PayoutStatus::where('application_id', $application_id)->first();
        }
        (new Slack(new Request(['title' => 'Check transfer status2', 'fields' => ['application_id' => $application_id, 'payoutdetails' => json_encode($payoutStatus)]])))->send();
        if(isset($documentDetails['user']['phase_cycle'])){
            $transferId = $application_id.'_'.($documentDetails['user']['phase_cycle']);
        }else{
            $transferId = $application_id;
        }

        $payout = new PayoutCFAPI(new Request(['id' => $application_id, 'transferId' => $transferId, 'referenceId' => $payoutStatus->referenceId ?? null, 'phase' => $documentDetails['user']['phase_cycle'] ?? 0]));
        $payoutResponseData = $payout->getTransferStatus();

        if($payoutResponseData['response'] && isset($payoutResponseData['response']->status) && $payoutResponseData['response']->status == 'SUCCESS'){

        }else if(!in_array($payoutResponseData['response']->status, ['FAILURE', 'FAILED'])){
            $this->InvokeCommunicationPayout($application_id,0,true);
            return true;
        }elseif($payoutResponseData['response']->status == 'FAILURE'){
            return true;
        }
    }

    public function getBankAccountDetails($application){

        if($application->merchant_id != 21) {
            $isCenterDisbursement = isset($application->application_element) && isset($application->application_element->merchant_center) && isset($application->application_element->merchant_center->id) ? 1 : 0;

            $bankDisbursal = $application->merchant_bank_details;
            if ($isCenterDisbursement) {
                $bankDisbursalStatus = isset($application->application_element) && isset($application->application_element->merchant_center) && isset($application->application_element->merchant_center->bank_details) && isset($application->application_element->merchant_center->bank_details->account_number) && $application->application_element->merchant_center->bank_details->account_number ? $application->application_element->merchant_center->bank_details : false;
                if ($bankDisbursalStatus) {
                    $bankDisbursal = $bankDisbursalStatus;
                }
            }
        }else{
            $bankDisbursal = Bank::where('application_id', $application->id)->first(['account_number','ifsc_code','name as account_holder','karza_response', 'bank_name', 'branch_name']);
            if(isset($bankDisbursal->karza_response) && $bankDisbursal->karza_response) {
                $bank_validation = json_decode($bankDisbursal->karza_response);
                if ((isset($bank_validation->result) && (isset($bank_validation->result->bankTxnStatus) && $bank_validation->result->bankTxnStatus == false) || (isset($bank_validation->result->bankResponse) && $bank_validation->result->bankResponse != 'Transaction Successful')) || !isset($bank_validation->result->bankResponse)) {
                    unset($bankDisbursal);
                    return false;
                }
            }else{
                unset($bankDisbursal);
                return false;
            }
        }

        return isset($bankDisbursal->account_number) && $bankDisbursal->account_number ? ['beneficiaryAccount' => $bankDisbursal->account_number, 'beneficiaryIFSC' => $bankDisbursal->ifsc_code, 'beneficiaryName' => $bankDisbursal->account_holder, 'beneficiaryBankName' => $bankDisbursal->bank_name, 'beneficiaryBranchName' => $bankDisbursal->branch_name] : false;
    }

    public function uploadToS3(ConsumerDocument $document, Request $request, $id)
    {

        if ($request->get('txt')) {
            $application = ConsumerApplication::find($id);

            $lender = Lenders::where('id', $application->lender_id)->first();
            $pdf = App::make('snappy.pdf.wrapper');
            $pdf->loadHTML($request->get('txt'))->setOption('encoding', 'UTF-8')->setPaper('a4')->setOrientation('portrait');
            if ($request->get('type') == 'Loan Agreement') {
                $pdf->setOption("footer-right", "Page [page] from [topage]");
                $pdf->setOption('footer-font-size', 10);
                $pdf->setOption('margin-bottom', 30);
            }
            $loan_agreement = $pdf->setOption('footer-html', view('admin.editor.footer', ['type' => $request->get('type'), 'lender' => $lender])->render());

            if ($request->has('original_name_file')) {
                $file_name = $request->get('type');
            } else {
                $file_name = str_replace(' ', '_', strtolower($request->get('type')));
            }

            $document->uploadToS3($file_name, $id, $loan_agreement->output());
        }
    }

    public function sendOSV($id, $originalSeenPDf, $document){

        if($originalSeenPDf) {
            $user = \App\ConsumerApplication::with('application_element', 'merchant', 'emi.offer')->where('id', $id)->first(['id', 'email', 'merchant_id', 'name', 'mobile_number', 'lender_id', 'co_applicant_name', 'co_applicant_mobile_number', 'co_applicant_email']);
            $merchant = Merchant::where('id', $user->merchant_id)->first(['email', 'merchant_name']);
            $email = explode(',', trim($merchant->email));
            if (isset($user->application_element->center_id) && $user->application_element->center_id != null && $user->application_element->center_id != "" && $user->application_element->center_id != 0) {
                $center = MerchantLocation::where('id', $user->application_element->center_id)->first(['email']);
                if (isset($center->email) && $center->email != "") {
                    $centeremail = explode(',', trim($center->email));
                    $email = array_merge($email, $centeremail);
                }
            }

            $document->uploadToS3('original_seen', $id, $originalSeenPDf['pdf']->output());


            if($user->merchant_id != 6543){
                $name = ucfirst(strtolower($user->name));
                $body = "Dear ".$merchant->merchant_name.",<br/><br/>
    Please find the OSV of ".$name." loan application and get back to us with the following:<br/><br/>
    1) Signed OSV<br/>
    2) KYC Self attested<br/>
    3) Confirmation of receipt of advance payment from customer.<br/>";


                if ($email) {
                    Mail::send('emails.reminders.basic_reminder',
                        ['body' => $body]
                        , function ($message) use ($originalSeenPDf, $email) {
                            $message->to($email)->subject('Original Seen & Verified');
                            $message->attachData($originalSeenPDf['pdf']->output(), $originalSeenPDf['fileName']);
                        });
                }
            }
        }
    }

    public function sendProForma($application_id, $partial_disbursed = false, $funBot = false)
    {

        $request = new Request();
        $request->request->add([
            'type' => 'Pro Forma Invoice',
            'bot' => true,
            'is_send_osv' => $funBot
        ]);
        $document = (new ConsumerDocument($request));
        $documentDetails = $document->getDocument($application_id);

        if ($documentDetails instanceof RedirectResponse) {
            (new Slack(new Request(['title' => __FUNCTION__ . ' Error', 'fields' => ['message' => Session::get('error'), 'content' => json_encode($documentDetails->getContent()), 'input' => json_encode($documentDetails->getRequest()->input()), 'id' => $application_id]])))->send();
            return false;
        }

        /* removing 'osv document from applicant's document section in admin panel' as per jira id 3546 */
        // if($funBot == false && isset($documentDetails['user']['send_da_on_checklist']) && $documentDetails['user']['send_da_on_checklist']){
        //     $this->sendOSV($application_id, $document->getOriginalSeenVerifiedMerchant($application_id), $document);
        //     return true;
        // }
        // $consumerDetails = ConsumerApplication::with('merchant')->where('id', $application_id)->first(['merchant_id']);
        // if ($consumerDetails->merchant->send_da == 1) {

        if (isset($documentDetails['user']['purpose_of_the_loan']) && $documentDetails['user']['purpose_of_the_loan'] != 'Personal Loan') {

            $application = ConsumerApplicationFiles::where('consumer_application_id', $application_id)->where('file_type','pan_card')->first(['id']);

            if(!isset($application->id)) {
                if (isset($documentDetails['user']['mandatory_document_list']) && $documentDetails['user']['mandatory_document_list']){
                    $documentDetails['user']['mandatory_document_list'] = array_merge($documentDetails['user']['mandatory_document_list'], ['pan_card']);
                }else{
                    $documentDetails['user']['mandatory_document_list'] = ['pan_card'];
                }
            }

            $application = ConsumerApplication::with('advisor')->where('id', $application_id)->first();
            $documentDetails['advisorEmail'] = $application->advisor->email ?? '';  // in case of emi checkout no advisor

            $data = [
                'txt' => view('admin.documents.per_forma_invoice', $documentDetails),
                'body' => view('emails.reminders.pro_forma', $documentDetails),
                'subject' => 'Disbursement Advice - ' . ucwords(strtolower($documentDetails['user']['customer_name'])),
                // 'cc_emails' => "ops@creditfair.in",
                'phase_cycle' => isset($documentDetails['user']['next_phase']) ? $documentDetails['user']['next_phase'] : -1,
                'slackmailcontent' => strip_tags(view('emails.reminders.pro_forma', $documentDetails)->render()),
                'document_Details' => $documentDetails,
                // 'cc_emails' => implode(',', [$documentDetails['advisorEmail'], 'ops@creditfair.in'])
            ];

            if (isset($documentDetails['user']['disbursement_phase'])) {
                $data['properties'] = $documentDetails['user'];
            }

            $request->request->add($data);
            // $document->ismerchantcommunication = true;
            // $document->cc_communication = "ops@creditfair.in";
            $document->downloadDocument($application_id);

            // if ($partial_disbursed) {
            //     $this->disbursementThrough = true;
            //     $this->disburseViaMultiStage($application_id, $documentDetails);
            // }
        }
        // }
    }

    public function disburseViaMultiStage($application_id, $documentDetails)
    {
        // (new Slack(new Request(['title' => 'Multistage error logs7', 'fields' => ['application_id' => $application_id]])))->send();
        $applicationElement = ConsumerApplicationElement::where('application_id', $application_id)->where('is_payout', 1)->first(['id']);

        if (isset($documentDetails['user']['disbursement_phase']) && (!isset($applicationElement->id) || $this->disbursementThrough)) {

            $this->disbursementThrough = false;

            if ($documentDetails['user']['phase_cycle'] > 0) { // > 0 because first invoice created while first disbursement
                if (date('Y-m-d') > '2019-03-31') {
//                    $this->generateInvoiceSubvention($application_id);
                    $this->invokeCommunication($application_id);
                    // (new Slack(new Request(['title' => 'Multistage error logs8', 'fields' => ['application_id' => $application_id]])))->send();
                }
            }

            $multiStageDisbursement = new MultiStageDisbursement();
            $multiStageDisbursement->disbursedPartially($application_id, $documentDetails);
        }
    }

    public function sendSanctionLetter($application_id, $test_bot = false)
    {
        try {
            $this->sendJuspayCommunication($application_id);
            $request = new Request();
            $request->request->add([
                'type' => 'Sanction Letter',
                'bot' => true,
                'test_bot' => $test_bot,
                'from_mail' => _env('CENTRALOPS')
            ]);

            $document = (new ConsumerDocument($request));
            $documentDetails = $document->getDocument($application_id);
            $documentDetails['pdf'] = 1;
            //return $documentDetails;

            /*$isProcessingFee = '';
            if (isset($documentDetails['user']['processing_fee_link'])){
                $isProcessingFee = $documentDetails['user']['processing_fee_link'];
            }*/
            //$application = ConsumerApplication::where('id',$application_id)->first();
            //$is_avanse = $application->isAvanse();
            $consumer_application_elements = ConsumerApplicationElement::where('application_id', $application_id)->first();
            if (!empty($documentDetails['lender']) && $documentDetails['lender']['id'] == ConsumerApplication::AVANSE_LENDER_ID) { // Avanse is lender
                $sanction_letter_view = 'admin.documents.avanse.sanction_letter_v3';
            } elseif (!empty($documentDetails['lender']) && $documentDetails['lender']['id'] == JMServices::$lender_id) { // ABFL is lender
                $sanction_letter_view = 'admin.documents.jm.sanction_letter';
            } elseif (!empty($documentDetails['lender']) && $documentDetails['lender']['id'] == Vivriti::$lender_id) { // Vivriti is lender
                $sanction_letter_view = 'admin.documents.vivriti.sanctionLetter_v_four';
            } elseif (!empty($documentDetails['lender']) && $documentDetails['lender']['id'] == Services::$lender_id) { // ABFL is lender
                $sanction_letter_view = 'admin.documents.abfl.sanction_letter';
            } elseif (!empty($documentDetails['lender']) && $documentDetails['lender']['id'] == \App\BlackSoil::$lender_id) { // BlackSoil is lender
                $sanction_letter_view = 'admin.documents.blacksoil.sanction_letter';
            } elseif (!empty($documentDetails['lender']) && $documentDetails['lender']['id'] == KMGP2P::$lender_id) { // KMGP2P is lender
                $sanction_letter_view = 'admin.documents.kmgp2p.sanction_letter_kmgp2p';
            } else {
                if ($consumer_application_elements->agreement_version == 2) {
                    $sanction_letter_view = 'admin.documents.sanctionLetter_v_four';
                } else {
                    $sanction_letter_view = 'admin.documents.sanctionLetter';
                }
            }


            $application = ConsumerApplicationFiles::where('consumer_application_id', $application_id)->where('file_type','pan_card')->first(['id']);
            if(!isset($application->id)) {
                $documentDetails['docs_pending'] = ['Pan Card' => 'pan_card'];
            }

            if (!is_array($documentDetails)) {
                return $documentDetails;
            }

            if($test_bot) {
                $application = ConsumerApplicationFiles::where('consumer_application_id', $application_id)->where('file_type', 'sanction_letter')->orderBy('created_at', 'desc')->first(['created_at']);

                $documentDetails['letter_date'] = isset($application->created_at) ? date('d-m-Y', strtotime($application->created_at)) : date('d-m-Y');
            }else{
                $documentDetails['letter_date'] = date('d-m-Y');
            }

            /*
                uncomment below code incase you want to view the sanction letter pdf file.
                It gets stored in storage/files directory
            */
            // $pdf = App::make('snappy.pdf.wrapper');
            // $camReport = $pdf->loadView($sanction_letter_view, $documentDetails)->setOption('encoding', 'UTF-8')->setPaper('a4')->setOrientation('portrait');
            // try {
            //     Storage::disk('s3_arn')->put('/testing/Sanaction-Letter1.pdf', $camReport->output());
            // } catch (\Exception $e) {
            //     return $e->getMessage();
            // }


            $data = [
                'txt' => view($sanction_letter_view, $documentDetails),
                'body' => view(BNPL::is($documentDetails['user']['merchant_id']) ? 'emails.reminders.sanction_letter_email_bnpl' : 'emails.reminders.sanction_letter_email_V1', $documentDetails),
                '_processing_fee_link' => isset($documentDetails['user']['processing_fee_link']) ? $documentDetails['user']['processing_fee_link'] : '',
                '_insurance_fee_link' => isset($documentDetails['user']['insurance_fee_link']) ? $documentDetails['user']['insurance_fee_link'] : '',
                '_advance_amount_link' => isset($documentDetails['user']['advance_amount_link']) ? $documentDetails['user']['advance_amount_link'] : '',
                'subject' => 'Loan '.$application_id.' Approved - Sanction Letter',
                'getEMandateLink' => isset($documentDetails['user']['getEMandateLink']) ? $documentDetails['user']['getEMandateLink'] : '',
                'document_Details'=> $documentDetails,
                //'processing_fee_link' => $isProcessingFee
            ];

            $request->request->add($data);
            return $document->downloadDocument($application_id);
        } catch (\Exception $e){
            $cwFactory = new CloudWatchLoggerFactory();
            $data = array('title' => 'Send Sanction Letter Error', 'application_id' => $application_id ?? '', 'error' => $e->getMessage(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString());
            $cwFactory->logger(json_encode($data));
        }
    }

    public function sendJuspayCommunication($application_id) {
        $vendor = ConsumerApplicationElement::where('application_id', $application_id)->first(['vendor_id']);
        if ($vendor->vendor_id == _env('JUSPAY_VENDOR')) {
            $entity = ['templateid' => '1307170374589776946', 'entityid' => Templates::$entityid];
            $consumerModel = ConsumerApplication::with('proFormaInvoice')->where('id', $application_id)->first();
            $mobile_number = '91' . wall_decrypt($consumerModel->mobile_number);
            $email = wall_decrypt($consumerModel->email);
            $merchant_name = Merchant::where('id', $consumerModel->merchant_id)->first(['merchant_name']);
            $sms_message = "Dear Customer, Your application id ".$consumerModel->proFormaInvoice->loan_application_no." for an Easy EMI plan for purchase at ".$merchant_name->merchant_name." has been approved! Congratulations and welcome to the Credit Fair family!<br/> Your Key Fact Statement and loan agreement is been generated by Credit Fair. <br/>Best Regards, Team Credit Fair 0996723504<br/>";
            send_sms($mobile_number, ['message'=>$sms_message, 'templateDetails' => $entity]);
        }
    }

    public function sendWelcomeLetter($application_id, $test_bot = false)
    {
        $request = new Request();
        $request->request->add([
            'type' => 'Welcome Letter',
            'test_bot' => $test_bot,
            'bot' => true
        ]);
        $document = (new ConsumerDocument($request));
        $gstDetails = $document->getDocument($application_id);
        // $pdf = App::make('snappy.pdf.wrapper');
        // $save_agreement_document_details = ['isInsuranceTaken' => 1, 'user' => $gstDetails['user'], 'id' => $application_id, 'data' => $gstDetails['data'], 'pdf' => 1, 'lender' => $gstDetails['lender'], 'combined_sl_la' => $gstDetails['combined_sl_la']];
        if(isset($gstDetails['is_bnpl']) && $gstDetails['is_bnpl']){
            return false;
        }
        // $view = 'admin.documents.welcome_v2';
        // dd($save_agreement_document_details['lender']['logo']);
        // $file = $pdf->loadView($view, $save_agreement_document_details)->setOption('encoding', 'UTF-8')->setPaper('a4')->setOrientation('portrait')->setOption('margin-bottom', 40)->output();
        // return $pdf->inline();
        if($gstDetails) {
            if ($test_bot) {
                if ($gstDetails instanceof RedirectResponse) {
                    return false;
                }
            }

            if (isset($gstDetails['user']['forProcessingFeeInvoice'])) {
                $gstDetails['user']['invoice'] = $gstDetails['user']['forProcessingFeeInvoice'];
            }

            if ($test_bot) {
                $application = ConsumerApplicationFiles::where('consumer_application_id', $application_id)->where('file_type', 'welcome_letter')->orderBy('created_at', 'desc')->first(['created_at']);

                if (!$application || !isset($application->created_at)) {
                    $application = StatusLogs::where('application_id', $application_id)->where('status', 'disbursed')->first(['created_at']);
                }

                $gstDetails['letter_date'] = isset($application->created_at) ? date('d F Y', strtotime($application->created_at)) : date('d F Y');
            } else {
                $gstDetails['letter_date'] = date('d F Y');
            }

            // dd($gstDetails);
            $data = [
                'txt' => view('admin.documents.welcome_v2', $gstDetails),
                'body' => view('emails.reminders.welcome', $gstDetails),
                'processing_fee_invoice_attributes' => $gstDetails,
                'subject' => 'Welcome to Credit Fair'
            ];

            if (!empty($gstDetails['lender']['id']) && ($gstDetails['lender']['id'] !== ConsumerApplication::AVANSE_LENDER_ID)) {
                // if avanse is not the lender then get the welcome letter attachement
                $data['txt'] = view('admin.documents.welcome_v2', $gstDetails);
            }

            if (isset($gstDetails['user']['consumer_emi']->processing_fee) && $gstDetails['user']['consumer_emi']->processing_fee > 0) {
                $data = array_merge($data, ['processing_fee_invoice' => view('admin.documents.processing_fee_invoice', $gstDetails)]);
            }

            $request->request->add($data);
            // $document->cc_communication = 'centralops@creditfair.in';
            $return = $document->downloadDocument($application_id);
            if ($test_bot) {
                return $return;
            }

        }
        return $gstDetails;
    }

    public function sendProcessingFeePDF($application_id, $isRoot = false, $send = false)
    {
        $request = new Request();
        $request->request->add([
            'type' => 'Welcome Letter',
            'bot' => true,
            'payment' => true
        ]);
        $document = (new ConsumerDocument($request));
        $gstDetails = $document->getDocument($application_id);
        $data = [
            'txt' => view('admin.documents.welcome_v2', $gstDetails),
            'processing_fee_invoice_attributes' => $gstDetails,
            'original_name_file' => true,
            'customer_email' => $gstDetails['user']['customer_email'],
            'customer_name' => $gstDetails['user']['customer_name']
        ];

        if (isset($gstDetails['user']['consumer_emi']->processing_fee) && $gstDetails['user']['consumer_emi']->processing_fee > 0) {
            $data = array_merge($data, ['processing_fee_invoice' => view('admin.documents.processing_fee_invoice', $gstDetails)]);

            $request->request->add($data);

            if ($isRoot) {
                $document = (new ConsumerDocument($request));
                $document->uploadProcessingFee($application_id, $send);
            }
        }
    }

    public function sendPreApprovalCommunicationV1($request_data, $listString, $subject, Request $request){

        if($request_data->email && (!in_array($request_data->merchant_id, explode(',', _env('NO_COMM_MERCHANT'))))) {
            $customer_application_link = asset('/application/login');

            $request->request->add(['data' => ['id' => $request_data->id]]);
            $email_verification = Customers::where('id', $request_data->applicant_id)->where('is_verified', 1)->first(['id']);

            $link = '';
            if (!isset($email_verification->id)) {
                $hash = new Hashids('Creditfair by CS', 20);
                $hash_id = $hash->encode($request_data->applicant_id);

                $link = asset('/email-verification/' . $hash_id);
            }

            $data = [
                'body' => view('emails.reminders.email_view', ['email_verification_link' => $link, 'link' => $customer_application_link, 'pending_documents' => $listString, 'email_verify' => $email_verification, 'monthly_income' => $request_data->monthly_income, 'company_name' => $request_data->company_name, 'employee_status' => $request_data->employee_status]),
                'subject' => $subject
            ];


            \Mail::send('emails.reminders.basic_reminder', [
                'body' => $data['body'], 'hideLogo' => true
            ], function ($message) use ($request_data, $data, $request) {
                $message->to($request_data->email)->subject($data['subject']);
                if ($request->has('email_to_merchant') && isset($request_data->merchant->email)) {
                    $em = explode(',', $request_data->merchant->email);
                    // array_push($em);
                    $em = array_filter($em);
                    $message->cc($em);
                } else {
                    // $message->cc('centralops@creditfair.in');
                }

            });
        }
    }


    public function getNotificationComments(Request $request){
        $user_id = $request->get('user_id');
        // $user_id="1";
        if($user_id) {
            $comments = Comments::select('comments.application_id', 'comments.comment')
            ->join('users', 'comments.user_id', '=', 'users.id')
            ->where('users.user_type', 2)
            ->whereIn('comments.application_id', function ($query) use ($user_id) {
                $query->select('id')
                    ->from('consumer_application')
                    ->where('created_by', $user_id)
                    ->where('state', '!=', 'disbursed');
            })
            ->orderBy('comments.created_at', 'DESC')
            ->get();
            // print $comments;
            $comment_logs = '';
            $count=0;
            foreach ($comments as $comment) {
                if ($count ==10){
                    break;
                }
                $application_commnet= $comment["comment"];
                if (strpos($application_commnet, "@" . $user_id) !== false){
                    $count +=1;
                $comment_created= str_replace("@", "", $comment["comment"]);
                $url = asset("admin/consumer-applications/edit/".$comment['application_id']);
                $comment_logs.='<div class="notification_content_div">
                                    <a  href="' .$url. '" style="text-decoration: none; color: inherit;" target="_blank">
                                        <div>
                                            <div>' . $comment_created . '</div>
                                            <div class="small text-gray-500">Applicaion ID->'. $comment["application_id"] .' </div>
                                        </div>
                                    </a>
                                </div>';
                }}
                // dd($comment_logs);
            if ($comment_logs != '') {
                return response()->json(['status' => 'OK', 'comments' => $comment_logs], 200);
                // return redirect()->to('/',['comments' => $comment_logs]);
            }else{
                return response()->json(['status' => 'FAIL']);
            }
        }else{
            return response()->json(['status' => 'FAIL']);
        }}

    public static function checkKarzaApproved($applicant_id, $applicant_type) {
        $status = false;
        $hwObjs = KarzaVideoWebhook::where('application_id', $applicant_id)
        ->where('applicant_type', $applicant_type)
        //->whereRaw("JSON_CONTAINS_PATH(data, 'one', '$.approvedByAuditor')")
        ->orderBy('created_at', 'DESC')
        ->get(['data']);

        foreach($hwObjs as $hwObj) {
            if (!$status && !empty($hwObj) && !empty($hwObj->data)) {
                $vkycStatus = json_decode($hwObj->data, 1);
                if (isset($vkycStatus['approvedByAuditor']) && $vkycStatus['approvedByAuditor'] == "ACCEPTED") {
                    $status = true;
                }
            }else if($status){
                break;
            }
        }
        unset($hwObjs);
        return $status;
    }

    public function generateCAMReportExcel(){
        $curl = curl_init();

        $user_id = Auth::user() ? Auth::user()->id : (Input::has('auth_user_id') ? Input::get('auth_user_id') : 107);
        $lender_id = Input::get('lender_id');

        //$type = 'cam_report_script';
        $type = "utkarsh_cam";

        curl_setopt_array($curl, array(
            CURLOPT_URL => _env('PY_SCRIPT_SERVER_HOST').'/api/'.$type,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => json_encode(['application_id' => (int)request()->get('id'), 'user_id' => (int)$user_id]),
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json'
            ),
        ));

        $response = curl_exec($curl);

        curl_close($curl);

        $status = (strpos($response,"error") !== false || strpos($response,"No data") !== false) ? 'FAIL' : 'OK';

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

    public function getCommunicationLog($id){
        if($id) {
            $data['communication_logs'] = $this->getCustomerCommunications($id);

            $communication_logs = '';
            foreach ($data['communication_logs'] as $notification) {
                $message = strpos($notification['purpose'], ' OTP ') !== false || strpos($notification['purpose'], 'verification code') !== false ? 'Verification OTP Sent.' : $notification['purpose'];
                $communication_logs .= '<tr>
                                                <td style="word-wrap: break-word;white-space: normal;  overflow-wrap: break-word; max-width: 400px;">' . $message . '</td>
                                                <td style="word-wrap: break-word;white-space: normal;  overflow-wrap: break-word; max-width: 200px;">' . $notification["by"] . '</td>
                                                <td style="word-wrap: break-word;white-space: normal;  overflow-wrap: break-word; max-width: 200px;">' . $notification["time"] . '</td>
                                                <td style="word-wrap: break-word;white-space: normal;  overflow-wrap: break-word; max-width: 200px;">' . $notification['type'] . '</td>
                                                <td style="word-wrap: break-word;white-space: normal;  overflow-wrap: break-word; max-width: 200px;">' . $notification['sent'] . '</td>
                                                <td style="word-wrap: break-word;white-space: normal;  overflow-wrap: break-word; max-width: 200px;">' . $notification['read'] . '</td>
                                                <td style="word-wrap: break-word;white-space: normal;  overflow-wrap: break-word; max-width: 200px;">' . $notification['read_time'] . '</td>
                                            </tr>';
            }


            $response['consumer_applications'] = ConsumerApplication::with('application_element', 'avanseByApplicant')->where('id', $id)->first(['id', 'pan_card', 'co_applicant_pan_card', 'lender_id', 'applicant_id', 'approved_amount','current_address_pincode', 'permanent_address_pincode', 'co_applicant_address_pincode','state', 'merchant_id']);

            $isNegativeAreaData = '';
            if ($negativeArea = $this->getNegativeAreaList($response)) {
                $isNegativeAreaData = $negativeArea;
            }

            $excludedFilesDigio = [
                'customer_signature_from_pan',
                'customer_photo_from_pan',
                'vkyc_video_'.$id.'_1',
                'customer_photo_from_aadhar',
                'digio_pan_report',
                'digio report applicant',
                'digio_aadhar_xml',
                'digio_data',
            ];

            $excludedFilesCoApplicantDigio = [
                'co_applicant_signature_from_pan',
                'co_applicant_customer_photo_from_pan',
                'co_applicant_customer_photo',
                'vkyc_video_'.$id.'_2',
                'customer_photo_from_aadhar',
                'co_applicant_digio_pan_report',
                'digio report coapplicant',
                'co_applicant_digio_aadhar_xml',
                'co_applicant_digio_data',
            ];
            $digioVKYC = DigioVKYC::where('application_id', $response['consumer_applications']->id)->whereNull('deleted_at')->get()->keyBy('applicant_type');
            $isDigioCompleted = $isDigioCompletedCoapp = false;
            $applicant_digio = $digioVKYC->get(1);
            $co_applicant_digio = $digioVKYC->get(2);

            if(isset($applicant_digio->id)){
                if($applicant_digio->applicant_type == 1){
                    if((isset($applicant_digio->kyc_status) && $applicant_digio->kyc_journey == "complete") && (isset($applicant_digio->kyc_status) && $applicant_digio->kyc_status == "approved")){
                        $isDigioCompleted = true;
                    }
                }
            }
            if(isset($co_applicant_digio->id)){
                if($co_applicant_digio->applicant_type == 2){
                    if((isset($co_applicant_digio->kyc_status) && $co_applicant_digio->kyc_journey == "complete") && (isset($co_applicant_digio->kyc_status) && $co_applicant_digio->kyc_status == "approved")){
                        $isDigioCompletedCoapp = true;
                    }
                }
            }
            $karzaApproved = $coKarzaApproved = false;
            $isCoApplicantExist = false;
            // check if applicant has been approved
            if (!empty($response['consumer_applications']->pan_card)) {
                if (self::VKYC_VENDOR == "karza") {
                    $karzaApproved = self::checkKarzaApproved($response['consumer_applications']->id, 1);
                }
            }

            // check if co-applicant has been approved
            if (!empty($response['consumer_applications']->co_applicant_pan_card)) {
                $isCoApplicantExist = true;
                if (self::VKYC_VENDOR == "karza") {
                    $coKarzaApproved = self::checkKarzaApproved($response['consumer_applications']->id, 2);
                }
            } else { // no co-applicant on the application
                $coKarzaApproved = true;
            }

            // Dynamic exclusion list based on application ID
            $excludedFiles = [
                "vkyc_pan_match_{$id}_1",
                "vkyc_aadhar_match_{$id}_1",
                "vkyc_video_{$id}_1",
                "KarzaV_report_applicant_{$id}_1",
                "signature_{$id}_1",
                "CUSTPHOTO_{$id}_1",
                "karzaV_report_applicant"
            ];

            $excludedFilesCoApplicant = [
                "vkyc_pan_match_{$id}_2",
                "vkyc_aadhar_match_{$id}_2",
                "vkyc_video_{$id}_2",
                "KarzaV_report_applicant_{$id}_2",
                "signature_{$id}_2",
                "CUSTPHOTO_{$id}_2",
                "karzaV_report_co_applicant"
            ];

            $data['files'] = ConsumerApplicationFiles::with('user', 'UtilityValidation', 'avanseDocument')
            ->where('consumer_application_id', $id)
            ->where('file_type', '!=', 'pirimid_analysis_json') 
            ->get();

            // Function to determine if a file is a VKYC file based on exclusion lists
            $isVKYCFile = function ($file) use ($excludedFiles, $excludedFilesCoApplicant) {
                return in_array($file->file_type, $excludedFiles) || in_array($file->file_type, $excludedFilesCoApplicant);
            };

            // Separate VKYC files from other files
            $vkycFiles = $data['files']->filter($isVKYCFile);
            $otherFiles = $data['files']->reject($isVKYCFile);

            // Group and un-duplicate VKYC files
            $groupedVKYCFiles = $vkycFiles->groupBy('file_type');
            $latestVKYCFiles = $groupedVKYCFiles->map(function (Collection $files) {
                return $files->sortByDesc('created_at')->first();
            });

            // Merge the latest VKYC files back with the other files
            $combinedFiles = $otherFiles->merge($latestVKYCFiles);

            $filteredFiles = $combinedFiles->filter(function ($file) use (
                $karzaApproved,
                $isCoApplicantExist,
                $coKarzaApproved,
                $isDigioCompleted,
                $isDigioCompletedCoapp,
                $excludedFiles,
                $excludedFilesCoApplicant,
                $excludedFilesDigio,
                $excludedFilesCoApplicantDigio,
                $id
            ) {
                $exclude = false;

                // Karza Logic
                if (ConsumerApplicationController::VKYC_VENDOR == "karza") {
                    // Main applicant exclusion
                    if (!$karzaApproved && in_array($file->file_type, $excludedFiles)) {
                        if ($file->file_type === "vkyc_video_{$id}_1" && is_null($file->doc_ref_id)) {
                            $exclude = true; // Exclude Karza VKYC video only if doc_ref_id is null
                        } elseif ($file->file_type !== "vkyc_video_{$id}_1") {
                            $exclude = true; // Exclude other Karza files for the main applicant
                        }
                    }

                    // Co-applicant exclusion
                    if ($isCoApplicantExist && !$coKarzaApproved && in_array($file->file_type, $excludedFilesCoApplicant)) {
                        if ($file->file_type === "vkyc_video_{$id}_2" && is_null($file->doc_ref_id)) {
                            $exclude = true; // Exclude Karza VKYC video only if doc_ref_id is null
                        } elseif ($file->file_type !== "vkyc_video_{$id}_2") {
                            $exclude = true; // Exclude other Karza files for the co-applicant
                        }
                    }
                }

                // Digio Logic
                if (!$isDigioCompleted && in_array($file->file_type, $excludedFilesDigio)) {
                    if ($file->file_type === "vkyc_video_{$id}_1" && !is_null($file->doc_ref_id)) {
                        $exclude = true; // Exclude Digio VKYC video only if doc_ref_id is NOT null
                    } elseif ($file->file_type !== "vkyc_video_{$id}_1") {
                        $exclude = true; // Exclude other Digio files for the main applicant
                    }
                }

                if (!$isDigioCompletedCoapp && in_array($file->file_type, $excludedFilesCoApplicantDigio)) {
                    if ($file->file_type === "vkyc_video_{$id}_2" && !is_null($file->doc_ref_id)) {
                        $exclude = true; // Exclude Digio VKYC video only if doc_ref_id is NOT null
                    } elseif ($file->file_type !== "vkyc_video_{$id}_2") {
                        $exclude = true; // Exclude other Digio files for the co-applicant
                    }
                }

                // Include the file only if it's not excluded
                return !$exclude;
            });

            // Assign filtered files back to the data array
            $data['files'] = $filteredFiles->values();


            $callsLogs = CallLogs::with('picked_by', 'received_by')->where('_id', $id)->where('id_type', 'application_id')->where(function ($query) {
                $query->Where('recording', '!=', '')
                    ->orWhere('status', 'in-progress');
            })->get(['id', '_id', 'user_id', 'recording', 'purpose', 'created_at', 'to', 'status']);
            foreach ($callsLogs as $indexCall => $callData) {
                $data['files'][] = $callData;
            }


            $item = array();
            $name = array();
            foreach ($data['files'] as $file) {
                if (isset($file->file_type)) {
                    $full_path = '/admin/consumer-application/get-documents/';
                    $short_path = isset($file->file_path) && !empty($file->file_path) ? $file->file_path : $id . '/' . $file->file_type . '.pdf';
                    $full_path .= $short_path;
                    $full_path = str_replace('//', '/', $full_path);
                    if (0 < count(array_intersect(array_map('strtolower', explode('.', $full_path)), ['jpeg', 'png', 'gif', 'pdf']))) {
                        array_push($item, $full_path);
                        array_push($name, $file->file_type);
                    }
                }
            }

            $data['filepaths'] = $item;
            $data['filenames'] = $name;


            foreach ($data['files'] as $id_key => $file) {
                if (strpos($file->file_type, 'aadhar_card') !== false) {
                    if (strpos($file->file_type, '_masked') !== false || $file->is_masked === 1) {
                        $data['files'][$id_key]['masked_doc'] = true;
                    } else {
                        $data['files'][$id_key]['masked_doc'] = false;
                    }
                }
                /*if ($file->file_type == 'pro_forma_invoice') {
                    if (!isset($_date) || (isset($_date) && strtotime($file->created_at) >= strtotime($_date))) {
                        if (isset($_id) && isset($data['files'][$_id]['latest_pro_forma_invoice'])) {
                            unset($data['files'][$_id]['latest_pro_forma_invoice']);
                        }
                        $_date = $file->created_at;
                        $_id = $id_key;
                        $data['files'][$_id]['latest_pro_forma_invoice'] = true;
                    }
                }*/

                if($file && $response['consumer_applications']->lender_id == AvanseServices::$lender_id) {
                    $isMapped = (new AvanseProcesses(new Request(['id' => $id, 'file_type' => $file->file_type, 'applicant_type' => $file->applicant_type, 'file_id' => $file->id])))->getAvanseDocumentMapping();
                    if($isMapped[0]) {
                        $data['files'][$id_key]['tp_key'] = $isMapped[0];
                        if(isset($isMapped[1]) && $isMapped[1]){
                            $data['files'][$id_key]['tp_key_av'] = $isMapped[1];
                        }
                    }
                }

                if($file && in_array($file->file_type, ['loan_agreement_esign', 'votar_id_front_masked', 'votar_id_back_masked', 'driving_license_masked', 'passport_front_masked', 'passport_back_masked', 'aadhar_card_masked', 'aadhar_card_back_masked']) && $response['consumer_applications']->lender_id == Services::$lender_id) {
                    $isMapped = (new ABFLController(new Request(['id' => $id, 'file_type' => $file->file_type, 'applicant_type' => $file->applicant_type, 'file_id' => $file->id])))->getDocumentMapping();
                    if($isMapped[0]) {
                        $data['files'][$id_key]['tp_key'] = $isMapped[0];
                        if(isset($isMapped[1]) && $isMapped[1]){
                            $data['files'][$id_key]['tp_key_av'] = $isMapped[1];
                        }
                    }
                }
                if($file && in_array($file->file_type, ['loan_agreement_esign','votar_id_front_masked','votar_id_back_masked','driving_license_masked', 'passport_front','passport_front_masked', 'passport_back','passport_back_masked', 'aadhar_card','aadhar_card_masked', 'aadhar_card_back','aadhar_card_back_masked', 'nach','pro_forma_invoice','pan_card','bank_statement_1','bank_statement_2','bank_statement_3','bank_statement_6','security_cheques']) && ($response['consumer_applications']->lender_id == LendBox::$lender_id || $response['consumer_applications']->lender_id == LendBoxLSP::$lender_id)) {
                    $isMapped = (new LendboxController(new Request(['id' => $id, 'file_type' => $file->file_type, 'applicant_type' => $file->applicant_type, 'file_id' => $file->id])))->getDocumentMapping();
                    if($isMapped[0]) {
                        $data['files'][$id_key]['tp_key'] = $isMapped[0];
                        if(isset($isMapped[1]) && $isMapped[1]){
                            $data['files'][$id_key]['tp_key_av'] = $isMapped[1];
                        }
                    }
                }
                if($file && ($response['consumer_applications']->lender_id == Singularity::$lender_id)) {
                    $isMapped = (new HomevilleController(new Request(['id' => $id, 'file_type' => $file->file_type, 'applicant_type' => $file->applicant_type, 'file_id' => $file->id])))->getDocumentMapping();
                    if($isMapped[0]) {
                        $data['files'][$id_key]['tp_key'] = $isMapped[0];
                        if(isset($isMapped[1]) && $isMapped[1]){
                            $data['files'][$id_key]['tp_key_av'] = $isMapped[1];
                        }
                    }
                }
                if($file && (in_array($file->file_type, ['credit_appraisal_memo','sanction_letter','self_attested_pan','self_attested_aadhar','consent_logs','customer_photo','loan_agreement_esign', 'votar_id_front', 'votar_id_front_masked', 'votar_id_back', 'votar_id_back_masked', 'driving_license', 'driving_license_masked', 'passport_front', 'passport_front_masked', 'passport_back', 'passport_back_masked', 'aadhar_xml', 'aadhar_card','aadhar_card_masked', 'aadhar_card_back','aadhar_card_back_masked', 'nach','pro_forma_invoice', 'pan_card', 'pan_card_masked', 'security_cheques', 'salary_slip', 'gst_certificate', 'finbit_analysis', 'equifax_report', 'call_recording', 'foir', 'panvalidation', 'personal discussion', 'itr', 'mca', 'cpv', 'osv', 'virtual_account', 'passbook_copy', 'proforma', 'pro_forma']) || str_contains(strtolower($file->file_type), 'report') || str_contains(strtolower($file->file_type), 'receipt') || str_contains(strtolower($file->file_type), 'applicant') || str_contains(strtolower($file->file_type), 'mandate') || str_contains(strtolower($file->file_type), 'attested') || str_contains(strtolower($file->file_type), 'statement') || str_contains(strtolower($file->file_type), 'video') || str_contains(strtolower($file->file_type), 'bank') || str_contains(strtolower($file->file_type), 'bill') || str_contains(strtolower($file->file_type), 'agreement')) && ($response['consumer_applications']->lender_id == KMGP2P::$lender_id)) {
                    $isMapped = (new KMGP2PController(new Request(['id' => $id, 'file_type' => $file->file_type, 'applicant_type' => $file->applicant_type, 'file_id' => $file->id])))->getDocumentMapping();
                    if($isMapped[0]) {
                        $data['files'][$id_key]['tp_key'] = $isMapped[0];
                        if(isset($isMapped[1]) && $isMapped[1]){
                            $data['files'][$id_key]['tp_key_av'] = $isMapped[1];
                        }
                    }
                }
                $dataFiles[$file->file_type][] = $file;
            }


            if(isset($dataFiles)) {
                foreach ($dataFiles as $_id_key => $dataFile) {
                    if (count($dataFile) > 1) {
                        unset($_date, $_id, $_id_);
                        foreach ($dataFile as $_id_key_ => $_dataFile) {
                            if (!isset($_date) || (isset($_date) && strtotime($_dataFile->created_at) >= strtotime($_date))) {
                                if (isset($_id) && isset($_id_) && isset($dataFiles[$_id][$_id_]['is_latest'])) {
                                    unset($dataFiles[$_id][$_id_]['is_latest']);
                                }
                                $_date = $_dataFile->created_at;
                                $_id = $_id_key;
                                $_id_ = $_id_key_;
                                $dataFiles[$_id][$_id_]['is_latest'] = true;
                            }
                        }
                    }
                }

                $data['files'] = [];
                foreach ($dataFiles as $_dataFiles) {
                    foreach ($_dataFiles as $_dataFile) {
                        $data['files'][] = $_dataFile;
                    }
                }

                $custFiles = (array) $data['files'];
                usort($custFiles, function ($a, $b) {
                    return strtotime($a['created_at']) - strtotime($b['created_at']);
                });

                $data['files'] = $custFiles;
            }

            $this->updateMerchantRepresentativeDetails($id);

            $data['consumer_applications'] = $response['consumer_applications'];

            $applicant = [];
            $co_applicant = [];
            $merchants = [];

            $merchants_options = ["pro_forma_invoice", "proforma", "original_seen_verified"];
            foreach($data['files'] as $file) {
                if($file->applicant_type == 2) {
                    $file->f_type = "Co-Applicant";
                    $co_applicant[] = $file;
                }elseif($file->applicant_type == 3 || in_array($file->file_type, $merchants_options)) {
                    $file->f_type = "Merchants";
                    $merchants[] = $file;
                }else {
                    $file->f_type = "Applicants";
                    $applicant[] = $file;
                }
            }
            $data['files'] = array_merge($applicant, $co_applicant, $merchants);
            $view = view('admin.scripts.file', $data)->render();

            $courier = (new CouriersController(new Request()));
            $data['couriers'] = $courier->getCourier($id, 2);
            $nach_status = $courier->NACHStatus($id);
            $viewCouriers = view('admin.scripts.couriers', $data)->render();


            $creditLimit = '';
            if (Input::get('credit_line') == 1) {
                try {
                    $creditLine = new CreditLine(new Request(['id' => $id]));
                    $data['creditLimit'] = $creditLine->getCreditData();
                } catch (\Exception $e) {
                    $data['creditLimit'] = 'Credit Limit Error Code - There is an issue with data (' . $e->getLine() . ')';
                }

                $data['creditDecision'] = Prediction::where('lid', $id)->get();

                $creditLimit = view('admin.scripts.credit_limit', $data)->render();
            }

            if(\Illuminate\Support\Facades\Session::has('Hide_Customer_Documents|-69')){
                $data['filenames'] = '';
                $data['filepaths'] = '';
            }

            return response()->json(['status' => 'OK', 'creditLimit' => $creditLimit, 'couriers' => $viewCouriers, 'nach_status' => $nach_status, 'filepaths' => $data['filepaths'], 'filenames' => $data['filenames'], 'communication_logs' => $communication_logs, 'isNegativeArea' => $isNegativeAreaData, 'files' => $view], 200);
        }
        return response()->json(['status' => 'FAIL']);
    }

    public function proformaSigningNotification($id)
    {
        $application = ConsumerApplication::with('merchant')->where('id', $id)->first();
        $request = [
            'type' => 'merchant',
            'id' => $application->merchant_id,
            'application_id' => $id,
            'notification_type' => 'proforma_signing',
            'title' => 'Sign off on the pro-forma of ' . $application->name,
            'body' => 'Dear ' . $application->merchant->merchant_name . ', please sign off on the pro-forma of ' . $application->name . ' for us to process the disbursement. Regards, Team Credit Fair',
            'deeplink' => '/edit-application/' . $id . '?click=proforma'
        ];
        new FCMNotification(new Request($request));
    }

    public function creditLimitNotification($id)
    {
        $application = ConsumerApplication::with('merchant')->where('id', $id)->first();
        try {
            $creditLine = new CreditLine(new Request(['id' => $id]));
            $creditData = $creditLine->getCreditData();
            $creditLimit = $creditData['max_loan_amount_to_sanction_basis_ml'] > $application->loan_amount ?
                str_replace('.00', '', money_format('%!i', round($creditData['max_loan_amount_to_sanction_basis_ml']))) : 'error';
        } catch (\Exception $e) {
            $creditLimit = 'error';
        }

        if($creditLimit !== 'error'){
            if($application->updated_by == 'consumer_app'){
                $consumer_request = [
                    'type' => 'user',
                    'id' => $application->user_id,
                    'application_id' => $id,
                    'notification_type' => 'credit_limit',
                    'title' => 'Higher loan eligibility for your application',
                    'body' => 'Pre-Approved amount ₹'.$creditLimit.'. Call us to know more',
                    'deeplink' => '/edit-application/' . $id
                ];
                new FCMNotification(new Request($consumer_request));
            }
            $request = [
                'type' => 'merchant',
                'id' => $application->merchant_id,
                'application_id' => $id,
                'notification_type' => 'credit_limit',
                'title' => 'Higher loan eligibility for ' . $application->name,
                'body' => 'Congratulations! '. $application->name . ' loan application can be approved for up to ₹'.$creditLimit.'.',
                'deeplink' => '/edit-application/' . $id
            ];
            new FCMNotification(new Request($request));
        }

    }

    public function callerInformation($id, $data)
    {
        $request = [
            'type' => 'user',
            'id' => $id,
            'application_id' => $id,
            'notification_type' => 'caller_information',
            'title' => $data['name'] . ' is calling you',
            'body' => 'Hi, ' . $data['name'] . ' is calling you regarding ' . $data['update'],
            'deeplink' => '/edit-application/' . $id . '?click=proforma'
        ];
        new FCMNotification(new Request($request));
    }

    public function waitingForDocumentNotification($id)
    {
        $application = ConsumerApplication::with('merchant')->where('id', $id)->first();
        $request = [
            'type' => 'merchant',
            'id' => $application->merchant_id,
            'application_id' => $id,
            'notification_type' => 'waiting_for_document',
            'title' => 'Documents required for ' . $application->name,
            'body' => 'Dear ' . $application->merchant->merchant_name . ', Documents for ' . $application->name . ' are pending. Please upload to ensure speedy disbursement. Regards, Team Credit Fair',
            'deeplink' => '/document-upload/' . $id
        ];
        new FCMNotification(new Request($request));
    }

    public function processingFeeNotification($id)
    {
        $application = ConsumerApplication::with('merchant')->where('id', $id)->first();
        $request = [
            'type' => 'merchant',
            'id' => $application->merchant_id,
            'application_id' => $id,
            'notification_type' => 'processing_fee',
            'title' => 'Please request ' . $application->name . ' to pay the loan processing fee',
            'body' => 'Dear ' . $application->merchant->merchant_name . ', Please request ' . $application->name . ' to pay the loan processing fee to facilitate speedy disbursement. Regards, Team Credit Fair',
            'deeplink' => '/edit-application/' . $id . '?click=processing_fee_dialog'
        ];
        new FCMNotification(new Request($request));
    }

    public function generateInvoice($application_id)
    {
        $data = ConsumerApplication::with('emi')->where('id', $application_id)->first();

        $gstDetails = (new ConsumerDocument(new Request()))->getGSTDetails(
            [
                'amount' => $data->emi->processing_fee,
                'state' => (isset($data->permanent_address_state) && !empty($data->permanent_address_state)) ? $data->permanent_address_state : (isset($data->current_address_state) && !empty($data->current_address_state) ? $data->current_address_state : '')
            ]
        );
        $amt = (isset($gstDetails[0])) ? $gstDetails[0]['amount'] : 0;
        if ($amt) {
            if ($gstDetails) {
                $response = array();
                foreach ($gstDetails as $gst) {
                    if (isset($gst['taxes']) && $gst['taxes'] == "CGST") {
                        $response['subvention_cgst'] = $gst['gst_amount'];
                    } elseif (isset($gst['taxes']) && $gst['taxes'] == "SGST") {
                        $response['subvention_sgst'] = $gst['gst_amount'];
                    } else {
                        $response['subvention_igst'] = $gst['gst_amount'];
                    }
                }
            }
            try {
                $type = 'processing_invoice';

                $invoice_id = $this->getInvoiceID($data, $type);


                $invoice = Invoices::where('application_id', $application_id)->where('type', $type)->whereNull('deleted_at')->first(['id']);
                $_data = [
                    'application_id' => $application_id,
                    'invoice_id' => $invoice_id,
                    'amount' => (isset($gstDetails[0])) ? $gstDetails[0]['amount'] : 0,
                    'net_amount' => (isset($gstDetails[0])) ? $gstDetails[0]['net_amount'] : 0,
                    'igst' => (isset($response['subvention_igst'])) ? $response['subvention_igst'] : 0,
                    'cgst' => (isset($response['subvention_cgst'])) ? $response['subvention_cgst'] : 0,
                    'sgst' => (isset($response['subvention_sgst'])) ? $response['subvention_sgst'] : 0,
                    'lender_id' => $data->lender_id,
                    'type' => $type,
                    'status' => 1,
                    'created_at' => Carbon::now()->toDateTimeString()
                ];

                if (!isset($invoice->id)) {
                    Invoices::insert(
                        $_data
                    );
                }
            } catch (\Exception $e) {

            }
        }
    }

    public function generateInvoiceSubvention($application_id)
    {
        $data = ConsumerApplication::with('merchant', 'emi', 'offer')->where('id', $application_id)->first();
        if(in_array($data->merchant_id,[4696, 4829, 4966, 6485, 6440])){
            //return ['net_amount' => 0, 'advance' => $data->emi->upfront_from_customer, 'ap' => $data->approved_amount];
            //return true;
        }
        if (isset($data->emi->subvention) && !empty($data->emi->subvention) && isset($data->merchant->is_gst) && $data->merchant->is_gst == 1 && isset($data->merchant->state) && !empty($data->merchant->state)) {

            $downPayment = 0;
            if($data->merchant->charge_subvention_remaining_amount){
                $downPayment = $data->emi->upfront_from_customer;
            }

            $subvention_amount = (($data->approved_amount - $downPayment) * $data->emi->subvention) / 100;
            $multiStageDisbursement = (new MultiStageDisbursement())->getSubventionInvoiceAmount($data, $subvention_amount);
            $subvention_amount = isset($multiStageDisbursement['subvention_amount']) ? $multiStageDisbursement['subvention_amount'] : $multiStageDisbursement;
            $gstDetails = (new ConsumerDocument(new Request()))->getGSTDetails(
                [
                    'amount' => $subvention_amount,
                    'state' => (isset($data->merchant->state) && !empty($data->merchant->state)) ? $data->merchant->state : '',
                ]
            );
            return ['net_amount' => $subvention_amount, 'advance' => $data->emi->upfront_from_customer, 'ap' => $data->approved_amount];
            $amt = (isset($gstDetails[0])) ? $gstDetails[0]['amount'] : 0;
            if ($amt) {
                if ($gstDetails) {
                    $response = array();
                    foreach ($gstDetails as $gst) {
                        if (isset($gst['taxes']) && $gst['taxes'] == "CGST") {
                            $response['subvention_cgst'] = $gst['gst_amount'];
                        } elseif (isset($gst['taxes']) && $gst['taxes'] == "SGST") {
                            $response['subvention_sgst'] = $gst['gst_amount'];
                        } else {
                            $response['subvention_igst'] = $gst['gst_amount'];
                        }
                    }
                }
                try {
                    $type = 'subvention_invoice';

                    $invoice = Invoices::where('application_id', $application_id)->where('type', $type);
                    if (isset($multiStageDisbursement['phase_id'])) {
                        $invoice = $invoice->where('phase_id', $multiStageDisbursement['phase_id']);
                    }
                    $invoice = $invoice->first(['id']);

                    if (!isset($invoice->id) && isset($gstDetails[0]['amount']) && $gstDetails[0]['amount'] > 0) {

                        return $gstDetails;

                        Invoices::insert(
                            [
                                'application_id' => $application_id,
                                'invoice_id' => $this->getInvoiceID($data, $type),
                                'amount' => (isset($gstDetails[0])) ? $gstDetails[0]['amount'] : 0,
                                'net_amount' => (isset($gstDetails[0])) ? $gstDetails[0]['net_amount'] : 0,
                                'igst' => (isset($response['subvention_igst'])) ? $response['subvention_igst'] : 0,
                                'cgst' => (isset($response['subvention_cgst'])) ? $response['subvention_cgst'] : 0,
                                'sgst' => (isset($response['subvention_sgst'])) ? $response['subvention_sgst'] : 0,
                                'lender_id' => $data->lender_id,
                                'type' => $type,
                                'phase_id' => isset($multiStageDisbursement['phase_id']) ? $multiStageDisbursement['phase_id'] : null,
                                'status' => 1,
                                'created_at' => Carbon::now()->toDateTimeString()
                            ]
                        );
                    }
                } catch (\Exception $e) {
                    (new \App\Slack(new Request(['title' => 'Invoice Creation Error', 'fields' => ['error' => $e->getMessage(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString(), 'application_id' => $application_id, 'id_type' => 'application_id']])))->send();
                }
            }
        }
        return ['net_amount' => 0, 'advance' => $data->emi->upfront_from_customer ?? 0, 'ap' => $data->approved_amount];
    }

    /* public function getInvoiceID($data){
        $invoice = Invoices::latest()->first(['invoice_id']);
        if(isset($invoice->invoice_id)){
            $invoiceSegment = isset(explode('-',$invoice->invoice_id)[0]) ? explode('-',$invoice->invoice_id)[0] : '';
            $invoiceID = isset(explode('CF',$invoiceSegment)[1]) ? explode('CF',$invoiceSegment)[1] : '';
            if($invoiceID < 167){
                $id = 168;
            }else {
                $id = $invoiceID + 1;
            }
        }else{
            $id = 147;
        }

        $concatstring = "";
        if (strlen($id) < 7) {
            $diff = 7 - strlen($id);
            for ($i = 0; $i < $diff; $i++) {
                $concatstring = $concatstring . "0";
            }
        }

        return 'CF'.$concatstring.$id.'-'.$this->getFinancialYear();
    }*/
    public function getInvoiceID($data, $type, $is_merchant=false)
    {
        $financialYear = $this->getFinancialYear($is_merchant);
        if($is_merchant) {
            $invoice = Invoices::where('lender_id', 2)->where('invoice_id', 'like', '%' . $financialYear . '%')->where('type',$type)
            ->where('merchant_id', '!=', 0)->orderBy('invoice_id', 'desc')->first(['invoice_id']);
        } else{
            $invoice = Invoices::where('lender_id', $data->lender_id)->where('invoice_id', 'like', '%-' . $financialYear)->where('type',$type)->whereNull('deleted_at')
            ->orderBy('invoice_id', 'desc')->first(['invoice_id']);
        }
        if (isset($invoice->invoice_id)) {
            $invoiceData = $is_merchant && strpos($invoice->invoice_id, '-S') ? explode('-S', $invoice->invoice_id) : (!$is_merchant && strpos($invoice->invoice_id, '-P') ? explode('-P', $invoice->invoice_id) : explode('-', $invoice->invoice_id));
            $invoiceID = isset($invoiceData[1]) ? (int)substr($invoiceData[1], 1) : '';
            $id = $invoiceID + 1;
        } else {
            $id = 1;
        }

        $concatstring = "";
        if($type == 'subvention_invoice') {
            if (strlen($id) < 6) {
                $diff = 6 - strlen($id);
                for ($i = 0; $i < $diff; $i++) {
                    $concatstring = $concatstring . "0";
                }
            }
        }else{
            if (strlen($id) < 7) {
                $diff = 7 - strlen($id);
                for ($i = 0; $i < $diff; $i++) {
                    $concatstring = $concatstring . "0";
                }
            }
        }

        if($type == 'subvention_invoice') {
            if($is_merchant){
                return 'CF-S2' . $concatstring . $id . '-' . $financialYear;
            }
            return '-';
        }else{
            if($type == 'insurance_invoice'){
                return 'CF-IN' . $concatstring . $id . '-' . $financialYear;
            }
            switch ($data->lender_id){
                case 2 :
                    return 'CF-P'. $concatstring . $id . '-' . $financialYear;
                case 3 :
                    return 'AV-P'. $concatstring . $id . '-' . $financialYear;
                case 4 :
                    return 'AB-P'. $concatstring . $id . '-' . $financialYear;
                case 5 :
                    return 'LB-P'. $concatstring . $id . '-' . $financialYear;
                case 10 :
                    return 'SC-P'. $concatstring . $id . '-' . $financialYear;
                case 7 :
                    return 'LL-P'. $concatstring . $id . '-' . $financialYear;
                case 11 :
                    return 'KM-P'. $concatstring . $id . '-' . $financialYear;
                case 9 :
                    return 'JM-P'. $concatstring . $id . '-' . $financialYear;
                case 12 :
                    return 'VC-P'. $concatstring . $id . '-' . $financialYear;
                case 16 :
                    return 'CG-P'. $concatstring . $id . '-' . $financialYear;
            }
        }
//        if($data->lender_id == 5) {
//            return 'L-' . $data->lender_id . $concatstring . $id . '-' . $financialYear;
//        }
//
//        return 'CF-' . $data->lender_id . $concatstring . $id . '-' . $financialYear;
    }

    public function getFinancialYear($is_merchant=false, $bp_invoice=false)
    {
//        $hyphen = '';
//        if(!$is_merchant){
//            $hyphen = '-';
//        }

        $m = date('m');
        if ($is_merchant && $m > 4 || (!$is_merchant && $bp_invoice && $m > 4) || (!$is_merchant && !$bp_invoice && $m >= 4)) {
            return date('y') . date('y', strtotime("+1 Year"));
        } else {
            return date('y', strtotime("-1 Year")) . date('y');
        }
    }

    public function  sendslackmessage($id, $status, $comment = '', $ispwa = "", $username = "", $coPartner = "")
    {
        $send_notification = false;
        /*if (env('APP_CONNECTION') == 0) {
            return true;
        }*/
        if ($id > 0) {

            if ($status == 'form completed') {
                $this->updateSystemReminders($id);
            }

            $data = ConsumerApplication::with('merchant', 'emi', 'proFormaInvoice','lender', 'advisor')->find($id);
            $customername = $data['name'];
            if (isset($data['merchant']['merchant_name'])) {
                $merchaneName = $data['merchant']['merchant_name'];
            } else {
                $merchaneName = "";
            }
            $loanAmount = $data['loan_amount'];
            $approved_amount = $data['approved_amount'];
            if (isset($data['emi']['upfront_from_credit_fair'])) {
                $NetDisbursementAmount = $data['emi']['upfront_from_credit_fair'];

                if ($NetDisbursementAmount == 0 && isset($data['merchant_id']) && $data['merchant_id'] == 21 && $approved_amount > 0) {
                    $NetDisbursementAmount = $approved_amount;
                }

                if (isset($data['proFormaInvoice']['processing_fee_by_merchant']) && $data['proFormaInvoice']['processing_fee_by_merchant'] == 1) {
                    if (isset($data['emi']['processing_fee']) && $data['emi']['processing_fee'] > 0) {
                        $NetDisbursementAmount = $NetDisbursementAmount - $data['emi']['processing_fee'];
                    }
                }

            } else {
                $NetDisbursementAmount = 0;
            }
            if ($username == "") {
                if (Auth::user()) {
                    $username = Auth::user()->name;
                } else if (Input::has('auth_user_id')) {
                    $auth = User::find(Input::get('auth_user_id'));
                    if (isset($auth->name)) {
                        $username = $auth->name;
                    }
                } else {
                    $username = "Customer";
                }
            }
            $applicationurl = asset("admin/consumer-applications/edit/" . $id);
            //$url = "https://hooks.slack.com/services/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";
            $field = array();
            array_push($field, array('title' => "Customer Name", "value" => $customername, "short" => true));
            array_push($field, array('title' => "Merchant Name", "value" => $merchaneName, "short" => true));
        } else {
            $applicationurl = '';
            $field = array();
        }
        if ($status == "waiting for decision") {
            $url = Slack::$CREDIT_DECISION;//"https://hooks.slack.com/services/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";
            array_push($field, array('title' => "Loan Amount", "value" => $loanAmount, "short" => true));
            array_push($field, array('title' => "Lender", "value" => $data['lender']['name'], "short" => true));
            $title = 'New Application waiting for Approval';
            $send_notification = true;
        } elseif ($status == "incomplete form") {
            if($ispwa == '- Lead Application') {
                $url = "https://hooks.slack.com/services/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";
                $title = 'New Lead Application received';
                $advisor_id = isset($data->advisor) && isset($data->advisor->id) ? $data->advisor->id : '';
                $slack_url = isset($data->advisor) && isset($data->advisor->slack_url) ? $data->advisor->slack_url : '';
                $segment = User::where('id', $advisor_id)->first(['id', 'name', 'slack_id']);
                    if(isset($segment->slack_id) && $segment->slack_id) {
                        $userString = 'Please acknowledge '.'<@' . $segment->slack_id . "|" . str_replace(' ', '', $segment->name) . '>';
                        (new Slack(new Request(['title' => $title,'fields'=>[],'group' => $slack_url,'tagging'=>[$advisor_id]])))->send();
                    }
            }elseif($coPartner !== ''){
                $url = "https://hooks.slack.com/services/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";
                $title = 'New Lead Application from Co-partner link';
                $advisor_id = isset($data->advisor) && isset($data->advisor->id) ? $data->advisor->id : '';
                if($advisor_id && isset($data->merchant) && $data->merchant->pre_status == 1 && $data->merchant->status == 'active') {
                    $segment = User::where('id', $advisor_id)->first(['id', 'name', 'slack_id']);
                    if(isset($segment->slack_id) && $segment->slack_id) {
                        $userString = 'Please acknowledge '.'<@' . $segment->slack_id . "|" . str_replace(' ', '', $segment->name) . '>';
                    }
                }
            }
        } elseif ($status == "form completed") {
            if($ispwa == '- By Consumer App'){
                $url = Slack::$APPLICATIONS_THROUGH_CONSUMER_APP;
            }else{
                $url = "https://hooks.slack.com/services/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";
                //$url = "https://hooks.slack.com/services/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";
            }
            array_push($field, array('title' => "Loan Amount", "value" => $loanAmount, "short" => true));
            $title = 'New Application received';
            $advisor_id = isset($data->advisor) && isset($data->advisor->id) ? $data->advisor->id : '';
            $slack_url = isset($data->advisor) && isset($data->advisor->slack_url) ? $data->advisor->slack_url : '';
            $segment = User::where('id', $advisor_id)->first(['id', 'name', 'slack_id']);
            if(isset($segment->slack_id) && $segment->slack_id) {
                $userString = 'Please acknowledge '.'<@' . $segment->slack_id . "|" . str_replace(' ', '', $segment->name) . '>';
                (new Slack(new Request(['title' => $title,'fields' => [],'group' => $slack_url,'tagging' => [$advisor_id]])))->send();
            }
        } elseif ($status == "approved") {
            $url = "https://hooks.slack.com/services/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";
            array_push($field, array('title' => "Loan Amount", "value" => $loanAmount, "short" => true));
            array_push($field, array('title' => "Approved Amount", "value" => $approved_amount, "short" => true));
            $title = 'Application Approved';
            $advisor_id = isset($data->advisor) && isset($data->advisor->id) ? $data->advisor->id : '';
            $slack_url = isset($data->advisor) && isset($data->advisor->slack_url) ? $data->advisor->slack_url : '';
//            if($advisor_id && isset($data->merchant) && $data->merchant->pre_status == 1 && $data->merchant->status == 'active') {
                $segment = User::where('id', $advisor_id)->first(['id', 'name', 'slack_id']);
                if(isset($segment->slack_id) && $segment->slack_id) {
                    $userString = 'Please acknowledge '.'<@' . $segment->slack_id . "|" . str_replace(' ', '', $segment->name) . '>';
//                    array_push($field, array('title' => "Tagged", "value" => $userString, "short" => true));
                    /*DM part*/
                    (new Slack(new Request(['title' => $title,'fields' => [],'group' => $slack_url,'tagging' => [$advisor_id]] )))->send();
                }
//            }
        } elseif ($status == "disbursed") {
            $url = "https://hooks.slack.com/services/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";
            array_push($field, array('title' => "Net Disbursement Amount", "value" => $NetDisbursementAmount, "short" => true));
            array_push($field, array('title' => "Lender", "value" => $data['lender']['name'], "short" => true));
            $title = 'Application Disbursed';
            $advisor_id = isset($data->advisor) && isset($data->advisor->id) ? $data->advisor->id : '';
            $slack_url = isset($data->advisor) && isset($data->advisor->slack_url) ? $data->advisor->slack_url : '';
            $segment = User::where('id', $advisor_id)->first(['id', 'name', 'slack_id']);
            if(isset($segment->slack_id) && $segment->slack_id) {
                $userString = 'Please acknowledge '.'<@' . $segment->slack_id . "|" . str_replace(' ', '', $segment->name) . '>';
                (new Slack(new Request(['title' => $title,'fields' => [],'group' => $slack_url,'tagging' => [$advisor_id]] )))->send();
            }
        } elseif ($status == "dis_approve_application") {
            $url = "https://hooks.slack.com/services/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";
            $statusLogs = StatusLogs::with('user')->where('application_id', $id)->where('status', 'waiting for decision')->first();
            $_userName = Auth::user() ? Auth::user()->id : (Input::has('auth_user_id') ? Input::get('auth_user_id') : 107);
            if (isset($statusLogs->user) && !empty($statusLogs->user)) {
                $_userName = $statusLogs->user->id;
            }
            $notify = $this->getNotifyName([$_userName]);
            array_push($field, array('title' => "Comment", "value" => $comment, "short" => true));
            $title = ' Verification Checklist Disapproved By ' . $username . '. ' . $notify . ' Please see';
        } elseif ($status == 'tech') {
            //$url = env('APP_CONNECTION') == 0 ? "https://hooks.slack.com/services/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" : "https://hooks.slack.com/services/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";
            $url = Slack::$STAGE_TESTING;
            array_push($field, array('title' => "getLine", "value" => $comment->getLine(), "short" => true));
            array_push($field, array('title' => "getMessage", "value" => $comment->getMessage(), "short" => true));
            array_push($field, array('title' => "getFile", "value" => $comment->getFile(), "short" => true));
            array_push($field, array('title' => "getTraceAsString", "value" => $comment->getTraceAsString(), "short" => true));
            $title = 'tech error';
        } elseif ($status == 'techBugMobile') {
            //$url = "https://hooks.slack.com/services/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";
            $url = Slack::$STAGE_TESTING;
            if ($comment['message']) {
                array_push($field, array('title' => "message", "value" => $comment['message'], "short" => true));
            }
            if ($comment['stack']) {
                array_push($field, array('title' => "stack", "value" => $comment['stack'], "short" => true));
            }
            if ($comment['info']) {
                array_push($field, array('title' => "info", "value" => $comment['info'], "short" => true));
            }
            if ($comment['url']) {
                array_push($field, array('title' => "url", "value" => $comment['url'], "short" => true));
            }
            if ($comment['status']) {
                array_push($field, array('title' => "status", "value" => $comment['status'], "short" => true));
            }
            if (isset($comment['error'])) {
                array_push($field, array('title' => "error", "value" => json_encode($comment['error']), "short" => true));
            }
            if (isset($comment['error_name'])) {
                array_push($field, array('title' => "error_name", "value" => json_encode($comment['error_name']), "short" => true));
            }
            if ($comment['user']) {
                array_push($field, array('title' => "User", "value" => $comment['user'], "short" => true));
            }
            $title = 'tech error';
        } elseif ($status == 'mismatchedPayment') {
            $url = "https://hooks.slack.com/services/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";
            if ($comment['bank']) {
                array_push($field, array('title' => "Bank", "value" => $comment['bank'], "short" => true));
            }
            if ($comment['name']) {
                array_push($field, array('title' => "Name", "value" => $comment['name'], "short" => true));
            }
            if ($comment['umrn']) {
                array_push($field, array('title' => "UMRN", "value" => $comment['umrn'], "short" => true));
            }
            if ($comment['payment_date']) {
                array_push($field, array('title' => "Payment Date", "value" => $comment['payment_date'], "short" => true));
            }
            if ($comment['amount']) {
                array_push($field, array('title' => "Amount", "value" => $comment['amount'], "short" => true));
            }
            if ($comment['status']) {
                array_push($field, array('title' => "Status", "value" => $comment['status'], "short" => true));
            }
            if ($comment['reason']) {
                array_push($field, array('title' => "Reason", "value" => $comment['reason'], "short" => true));
            }
            $title = 'Payment Mismatch';
        } else {
            $url = "https://hooks.slack.com/services/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";
            array_push($field, array('title' => "Net Disbursement Amount", "value" => $NetDisbursementAmount, "short" => true));
            $title = 'New Application waiting for Disbursement';
        }
        if ($ispwa != "") {
            $title .= " " . $ispwa;
        }
        if ($applicationurl) {
            array_push($field, array('title' => "Application Link", "value" => $applicationurl, "short" => true));
        }
        // $url = "https://hooks.slack.com/services/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"; // for testing

        if ((env('APP_CONNECTION') == 0)) {
            $url = "https://hooks.slack.com/services/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";
        }



        if($send_notification) {
            $data = [];
            foreach($field as $item){
                $data = array_merge($data, [$item['title'] => $item['value']]);
            }
            (new \App\Slack(new Request(['title' => $title, 'fields' => $data, 'group' => $url])))->send();
        }
        return true;

        $payload = json_encode(array('text' => $title, "username" => $username, 'attachments' => array(array('fields' => $field),  array('text' => $userString ?? ''))));
        $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);
        $err = curl_error($curl);

        curl_close($curl);

        if ($err) {
            echo "cURL Error #:" . $err;
        } else {
            //echo $response;
        }
    }

    public function getNotifyName($names)
    {
        $users = [
            26 => '@UCFJ9K36W',
            10 => '@UCFCJ88TE',
            36 => '@UCRQ91F5G',
            40 => '@UCMCRNG77',
            6 => '@UCMCRNG77',
        ];
        $userString = '';
        foreach ($names as $name) {
            if (isset($users[$name])) {
                $userString .= '<' . $users[$name] . "|" . $name . '> ';
            }
        }
        return $userString;
    }

    public function enachresponse($id)
    {
        $hashids = new Hashids('Creditfair by CS', 20);
        $application_ids = $hashids->decode($id);
        Mandate::where('consumer_application_id', $application_ids[0])->where('status', 'active')->update(['status' => 'submitted']);
        $data = array("application_ids" => $application_ids);
        return view('front.application.enach-congrats', $data);
    }

    public function saveFOIR(Request $request)
    {
        $data = $request->get('data');
        if ($data) {
            foreach ($data as $item) {
                $app_id = $item['application_id'] ?? 0;
                if ($item['id'] > 0) {
                    $foirData = FOIR::find($item['id']);
                    $oldFoirData = $foirData->InstallmentAmount;
                    $foirData->InstallmentAmount = $item['InstallmentAmount'];
                    $foirData->updated_by = Auth::user()->id;
                    $foirData->reason_info = $item['reason_info'] ?? null;
                    $foirData->save();

                    if($oldFoirData != $item['InstallmentAmount']){
                        ContentLogger::insert([
                            'application_id' => $item['application_id'],
                            'data' => json_encode(['installmentamount_'.$item['id'] => ['old'=>$oldFoirData,'new'=>$item['InstallmentAmount']]]),
                            'status' => $item['status'],
                            'created_at' => Carbon::now()->toDateTimeString(),
                            'user_id' => Auth::user()->id
                        ]);
                    }

                    // FOIR::where('id', $item['id'])->update(['InstallmentAmount' => $item['InstallmentAmount'], 'updated_by' => Auth::user()->id, 'reason_info' => $item['reason_info'] ?? null]);
                } else {

                    if ((isset($item['credit_id']) && $item['credit_id'] == 0) || !isset($item['credit_id'])) {
                        $creditReport = CreditReport::where('application_id', $item['application_id'])->first();
                        $credit_id = isset($creditReport->id) ? $creditReport->id : 0;
                    } else {
                        $credit_id = $item['credit_id'];
                    }
                    $insertnew = true;
                    if ($item['AccountType'] == "Credit Fair EMI") {
                        $cffoir = FOIR::where("AccountType", $item['AccountType'])->where("application_id", $item['application_id'])->first(['id','InstallmentAmount']);
                        if (isset($cffoir->id)) {
                            $insertnew = false;
                            if ($cffoir->InstallmentAmount != $item['InstallmentAmount']) {
                                ContentLogger::insert([
                                    'application_id' => $item['application_id'],
                                    'data' => json_encode(['installmentamount_'.$item['id'] => ['old'=>$cffoir->InstallmentAmount,'new'=>$item['InstallmentAmount']]]),
                                    'status' => $item['status'],
                                    'created_at' => Carbon::now()->toDateTimeString(),
                                    'user_id' => Auth::user()->id
                                ]);

                                FOIR::where('id', $cffoir->id)->update(['InstallmentAmount' => $item['InstallmentAmount'], 'updated_by' => Auth::user()->id]);
                            }
                        }
                    }
                    if ($insertnew == true) {
                        FOIR::insert([
                            'application_id' => $item['application_id'],
                            'credit_id' => $credit_id,
                            'AccountType' => $item['AccountType'],
                            'ApprovedAmount' => $item['ApprovedAmount'],
                            'Balance' => $item['Balance'],
                            'InterestRate' => 0,
                            'RepaymentTenure' => 0,
                            'InstallmentAmount' => $item['InstallmentAmount'],
                            'cc_loan' => $item['cc_loan'],
                            'DateOpened' => null,
                            'DateClosed' => null,
                            'OwnershipType' => '',
                            'applicant_type' => $item['applicant_type'],
                            'Institution' => '',
                            'isOpened' => 1,
                            'LastPayment' => null,
                            'PastDueAmount' => null,
                            'dpd' => json_encode([]),
                            'reason_info' => $item['reason_info'] ?? null,
                            'created_by' => Auth::user()->id,
                            'created_at' => Carbon::now()->toDateTimeString()
                        ]);
                    }
                }
            }

        }


        return response()->json(['message' => 'Foir Generated Successfully'], 200);
    }

    public function checkMandates($id)
    {
        if ($id) {
            $mandates = Mandate::where('consumer_application_id', $id)->whereIn('status', ['active', 'submitted'])->get();
            $statusIFNotRepeat = false;
            if (count($mandates) > 0 && $statusIFNotRepeat) {

                $table = '<div style="color:red;padding-bottom: 7px;">*Please deactivate below NACH to proceed further</div><table class="table table-striped"><tr><th>Amount</th><th>Status</th><th>Action</th></tr>';
                foreach ($mandates as $mandate) {
                    $table .= '<tr><td>' . $mandate->mandate_amount . '</td><td>' . $mandate->status . '</td><td><div class=""><a href="/admin/mandate/edit/' . $mandate->id . '?status=cancel" style="text-decoration: none;">Deactivate</a></div></td></tr>';
                }
                $table .= '</table>';

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

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

    public function deleteImproperDocument(Request $request){
        if($request->get('application_id')){
            ConsumerApplicationFiles::where('consumer_application_id', $request->get('application_id'))->where('file_type','self_attested')->delete();
            return response()->json(['status' => 'OK']);
        }
        return response()->json(['status' => 'FAIL']);
    }

    public function deleteDocument(Request $request){

        $errorMessage = '';
        if($request->get('id')){
            $user = User::where('id',$request->get('user_id'))->first(['name']);
            $application = ConsumerApplication::with('advisor')->where('id', $request->get('application_id'))->first();
            $file = ConsumerApplicationFiles::where('id', $request->get('id'))->first(['id','file_path','file_type']);

            if(!isset($file->file_path)){
                return response()->json(['status' => 'FAIL', 'message' => 'File path not found']);
            }

            if($application->lender_id == AvanseServices::$lender_id) {
                $deleteFinDocument = (new AvanseProcesses(new Request(['id' => $request->get('application_id'), 'consumer_application_file_id' => $request->get('id'), 'doc' => $file->file_type])))->deleteDocument();

                if (!is_array($deleteFinDocument) && is_int($deleteFinDocument)) {
                    $errorMessage = 'Avanse Document Deleted';
                } else {
                    $errorMessage = is_array($deleteFinDocument) ? implode("\n", $deleteFinDocument) : $deleteFinDocument;
                }
            }
            $deleted_name = explode('/', $file->file_path);

            $filePath = 'https://'._env('AWS_BUCKET')._env('AWS_ORIGIN') . '/' .$file->file_path;
            $file_path = '/' . $request->get('application_id') . '/deleted/' . $deleted_name[count($deleted_name) - 1];
            ConsumerApplicationFiles::where('id', $request->get('id'))->update(['deleted_by' => $request->get('user_id')]);
            ConsumerApplicationFiles::where('id', $request->get('id'))->delete();
            $advisor_id = isset($application->advisor) && isset($application->advisor->id) ? $application->advisor->id : '';
            (new Slack(new Request(['title' => 'Document Deleted', 'fields' => ['Deleted By' => $user->name, 'Customer Name' => $application->name, 'Document Name' => ucwords(str_replace('_',' ',$file->file_type)), 'application_id' => $request->get('application_id')], 'group' => 'customer_documents', 'tagging' => [$advisor_id]])))->send();
            if ($file->file_type == 'consent_logs') {
                DB::update("UPDATE consumer_application_element set is_consent = 0 where application_id = ?",[$request->get('application_id')]);
            }
            if ($file->file_type == 'co_app_consent_logs') {
                DB::update("UPDATE consumer_application_element set is_co_app_consent = 0 where application_id = ?",[$request->get('application_id')]);
            }
            return response()->json(['status' => $errorMessage ? 'FAIL' : 'OK', 'message' => $errorMessage]);
        }
        return response()->json(['status' => 'FAIL', 'message' => $errorMessage]);
    }

    public function softDeleteS3($fileObject){
        if($fileObject !== null) {
            $user_id = Auth::user() ? Auth::user()->id : (\request()->get('auth_user_id') ? \request()->get('auth_user_id') : 107);
            $deleted_name = explode('/', $fileObject->file_path);

            $filePath = 'https://' . _env('AWS_BUCKET') . _env('AWS_ORIGIN') . '/' . $fileObject->file_path;
            $file_path = '/' . $fileObject->consumer_application_id . '/deleted/' . $deleted_name[count($deleted_name) - 1];
            $s3 = Storage::disk('s3');
            $s3->put($file_path, $filePath);
            $s3->delete($fileObject->file_path);

            ConsumerApplicationFiles::where('id', $fileObject->id)->update(['deleted_by' => $user_id]);
            ConsumerApplicationFiles::where('id', $fileObject->id)->delete();
        }
    }

    public function checkMandatesForStatusChange($id, $status)
    {
        $appplication_status = ConsumerApplication::where('id', $id)->first(['state', 'applicant_id']);
        $previous_mandate_id = (new NachService(new Request()))->isCustomerHasPreviousActiveNach($appplication_status->applicant_id);
        if (!$previous_mandate_id) {
            $previous_status = (isset($appplication_status->state)) ? $appplication_status->state : "";

            if ($status == 'disbursed' && $previous_status == 'nach registered') {
                $mandates = Mandate::where('consumer_application_id', $id)->where(function ($query) {
                    $query->where('umrn', '!=', '')->whereNotNull('umrn')->orwhere('status', 'active');
                })->where('status', 'active')->get();
                //$mandates = Mandate::where('consumer_application_id', $id)->where('umrn','!=','')->whereNotNull('umrn')->where('status', 'active')->get();
                $statusIFNotRepeat = false;
                if (count($mandates) > 0 && $statusIFNotRepeat) {
                    $table = '<div style="color:red;padding-bottom: 7px;">*Please deactivate below NACH to proceed further</div><table class="table table-striped"><tr><th>Amount</th><th>Status</th><th>Action</th></tr>';
                    foreach ($mandates as $mandate) {
                        $table .= '<tr><td>' . $mandate->mandate_amount . '</td><td>' . $mandate->status . '</td><td><div class=""><a href="/admin/mandate/edit/' . $mandate->id . '?status=cancel" style="text-decoration: none;" target="_blank">Deactivate</a></div></td></tr>';
                    }
                    $table .= '</table>';
                    return \response()->json(['status' => 'OK', 'data' => $table]);
                }
            } elseif ($status == 'nach registered') {
                $mandates = Mandate::where('consumer_application_id', $id)->where('umrn', '!=', '')->whereNotNull('umrn')->where('status', 'active')->get();
                if (count($mandates) < 1) {
                    $url = asset("admin/getallmandates/" . $id);
                    $data = "You don't have any mandate active for this customer. Please click on button below to create a mandate <br>
                <a href=$url target='_blank'> <button type='button' class='btn btn-primary i_checked_dialog'>Mandate</button></a>

</p>";
                    return \response()->json(['status' => 'OK', 'data' => $data]);
                }
            }
        }

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

    public function disApprovedApplication(Request $request)
    {
        $__status = 'FAIL';
        if ($request->has('application_id')) {
            $__status = 'OK';

            $pureComment = $request->get('comment');
            if ($request->get('comment')) {
                $getComment = (new ApiController())->getPureComment($request);
                $pureComment = $getComment['comment'];

                if ($getComment['users']) {
                    $usersContacts = User::whereIn('id', $getComment['users'])->get(['mobile_number']);

                    $application = ConsumerApplication::where('id', Input::get('application_id'))->first(['id', 'name', 'mobile_number']);

                    $link = "https://creditfair.in/admin/consumer-applications/edit/" . $application->id;

                    $commenter = Auth::user() ? Auth::user()->name : 'Credit Fair';

                    $pureCommentNew = "Customer Name: $application->name\nCommented By :$commenter\nApplication Link: $link\n$pureComment";
                    foreach ($usersContacts as $contact) {
                        sendWhatsAppMessage($contact->mobile_number, $pureCommentNew);
                    }
                }
            }

            $this->sendslackmessage($request->get('application_id'), 'dis_approve_application', $pureComment);
            if ($request->has('comment') && !empty($request->get('comment'))) {
                $comment = new Comments();
                $comment->application_id = $request->get('application_id');
                $comment->user_id = Auth::user()->id;
                $comment->comment = $pureComment;
                $comment->show_merchant = ($request->has('show_merchant') && $request->get('show_merchant')) ? 1 : 0;
                $comment->show_consumer = ($request->has('show_consumer') && $request->get('show_consumer')) ? 1 : 0;
                $comment->save();
            }

            $application = ConsumerApplication::find($request->get('application_id'));
            $status = $this->getArrayBackValidate($application->state);
            if (in_array('approved', $status)) {
                // sent to approved
                $_status = 'approved';
            } else {
                //sent to in-process
                $_status = 'in-process';
            }
            //$_status = 'in-process';
            $application->state = $_status;
            $application->save();

            StatusLogs::insert([
                'application_id' => $application->id,
                'user_id' => Auth::user()->id,
                'status' => $_status,
                'created_at' => Carbon::now()->toDateTimeString()
            ]);
            //return $this->updateApplicationStatus($request->get('application_id'), $_status);
        }

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

    public function getArrayBackValidate($state)
    {
        return $this->getPastLogs($state);
    }

    public function updateApplicationStatus($id, $status, $insideCall = false)
    {
        $this->current_status = $status;
        return $this->updateStatus($id, $insideCall);
        /*\App\ConsumerApplication::where('id',$id)
            ->update(['state'=>$this->status[$status]]);

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

    public function getAccountAggregatorLink(Request $request){

        if ($request->has('application_id')) {
            $redirect_url = $request->get('redirect_url');
            $hashed_id = $request->get('application_id');
            $hashids = new Hashids('Creditfair by CS', 20);
            $application_id = $hashids->decode($hashed_id)[0];
            $application = ConsumerApplication::where('id', $application_id)->first(['mobile_number']);
            return (new AccountAggregator($request->merge(
                ['mobile_number' => $application->mobile_number,
                'id' => $application_id,
                'redirection_url' => $redirect_url]
            )))->initiate();
        }
        else {
            $application = ConsumerApplication::where('id', $request->get('id'))->first(['mobile_number']);
            return (new AccountAggregator($request->merge(
                ['mobile_number' => $application->mobile_number]
            )))->initiate();
        }
    }

    public function getNewPaymentLink(Request $request){
        $frontController = new FrontController($request);
        $response = $frontController->getFeesData($request->get('id'));
        return response()->json(['status' => 'OK', 'response' => $response], 200);
    }

    // sends payment links to customer when the approved amount is revised
    // called by the index blade, revise documents
    public function sendNewPaymentLink(Request $request) {
        try {
            $cwFactory = new CloudWatchLoggerFactory();
            $application_id = $request->get('id');
            $customerName = $request->get('name');
            $customerMobileNumber = wall_decrypt($request->get('mobile'));
            $type = $request->get('type');
            $amount = $request->get('amount');
            $approved_amount = $request->get('approved_amount');
            $link = Shortio::getUrl(asset('redirect/?link=' . base64_encode($request->get('link'))));
            $trigger_log = ContentLogger::where('application_id', $application_id)->where('status', 'approved')
                ->where(function($query) {
                    $query->where('data', 'like', '%approved_amount%')
                        ->orWhere('data', 'like', '%offer_id%');
                })
                ->orderBy('created_at', 'desc')
                ->first();
            if (isset($link)) {
                if ($type == 'total_payment') {  // send processing fee to customer
                    $is_revised = false;
                    if (isset($trigger_log)) {
                        $is_revised = true;
                        if (str_contains($trigger_log->data, 'approved_amount')) {
                            $entity = ['templateid' => '1307173700967100570', 'entityid' => Templates::$entityid];
                            $Message = 'Dear '.$customerName.', Congratulations! Your loan amount has been revised to Rs. '.$approved_amount.'. Please pay the revised amount of Rs. '.$amount.' towards outstanding obligations by clicking on the link '.$link.' to ensure the timely processing of your application. - Credit Fair';
                            send_sms($customerMobileNumber, [
                                'message' => $Message,
                                'id' => $request->get('id'),
                                'id_type' => 'application_id',
                                'args' => [$link],
                                'templateDetails' => $entity,
                                'service' => 'quicksmart'
                            ]);
                        } else if (str_contains($trigger_log->data, 'offer_id')) {
                            $entity = ['templateid' => '1307173700982358290', 'entityid' => Templates::$entityid];
                            $Message = 'Dear '.$customerName.', Congratulations! Your loan offer has been revised. Please pay the revised amount of Rs. '.$amount.' towards outstanding obligations by clicking on the link '.$link.' to ensure the timely processing of your application. - Credit Fair';
                            send_sms($customerMobileNumber, [
                                'message' => $Message,
                                'id' => $request->get('id'),
                                'id_type' => 'application_id',
                                'args' => [$link],
                                'templateDetails' => $entity,
                                'service' => 'quicksmart'
                            ]);
                        } else {
                            $is_revised = false;
                        }
                    }
                } else {
                    $is_revised = false; // Not a total_payment type
                }
                return \response()->json(['status' => 'OK', 'is_revised' => $is_revised]);
            }
            $cwFactory->logger(json_encode(['application id' => $application_id, 'type' => $type, 'amount' => $approved_amount]));
            return \response()->json(['status' => 'FAIL']);
       } catch(\Exception $e) {
            $cwFactory->logger(json_encode(['application id' => $application_id, 'message' => $e->getMessage(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString()]));
            return \response()->json(['status' => 'FAIL']);
       }
    }

    public function sendCPVMailer(Request $request){

        $CPVMailerData = $request->get('cpv_data');
        $CPVMailerData = array_merge($CPVMailerData, ['user_id' => $request->get('user_id'), 'application_id' => $request->get('id'), 'created_at' => Carbon::now()->toDateTimeString()]);
        $CPVMailerDataObject = CPVMailer::insertGetId($CPVMailerData);


        if(env('APP_CONNECTION')) {
            $email = ['vishwanath.kate@pamac.com', 'sayli.a@pamac.com'];
            $cc = ['nicholas.lobo@pamac.com', 'centralops@creditfair.in'];
        }else{
            $email = ['pratik@creditfair.in'];
            $cc = ['sunil@creditfair.in'];
        }

        $application = ConsumerApplication::with(array('advisor' => function($query) {
            $query->select('id','name','email');
        }))->where('id', $request->get('id'))->first(['id', 'created_by']);

        if(isset($application->advisor) && isset($application->advisor->email)){
            array_push($cc, $application->advisor->email);
        }

        if($CPVMailerDataObject) {
            Mail::send('emails.reminders.basic_reminder',
                ['body' => $request->get('html'), 'customFooter' => 1]
                , function ($message) use ($email, $cc) {
                    //$message->to(['sunil@creditfair.in', 'himanshu@creditfair.in', 'dinesh@creditfair.in'])->subject('CPV / Document collection');
                    $message->to($email)->subject('CPV / Document collection');
                    $message->cc($cc);
                });

            return \response()->json(['status' => 'OK', 'message' => 'CPV / Document collection mail sent successfully!']);
        }

        return \response()->json(['status' => 'FAIL', 'message' => 'Failed to sent mail. Please try after sometime']);
    }

    public function getCPVData(Request $request){
        $id = $request->get('id');
        $user_id = $request->get('user_id');

        $application = ConsumerApplication::with(array('merchant' => function($query) {
            $query->select('id','merchant_name');
        }))->with(array('proFormaInvoice' => function($query) {
            $query->select('id', 'application_id','loan_application_no');
        }))->with(array('advisor' => function($query) {
            $query->select('id','name','mobile_number');
        }))->where('id', $id)->first(['id', 'created_by','current_address_line_1', 'current_address_city', 'current_address_landmark', 'current_address_pincode', 'current_address_state','name','co_applicant_name','co_applicant_mobile_number','mobile_number','merchant_id']);

        $response = [
            'current_address_line_1' => $application->current_address_line_1.' '.$application->current_address_landmark.' '.$application->current_address_city.' '.$application->current_address_state.' '.$application->current_address_pincode,
            'merchant_name' => $application->merchant ? $application->merchant->merchant_name : '',
            'loan_application_no' => $application->proFormaInvoice ? $application->proFormaInvoice->loan_application_no : '',
            'name' => $application->name,
            'co_applicant_name' => $application->co_applicant_name,
            'co_applicant_mobile_number' => wall_decrypt($application->co_applicant_mobile_number),
            'mobile_number' => wall_decrypt($application->mobile_number),
            'advisor' => $application->advisor ? $application->advisor->name : '',
            'advisor_number' => $application->advisor ? wall_decrypt($application->advisor->mobile_number) : '',
            'date_receipt' => Carbon::now()->toDateTimeString(),
        ];

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

    public function updateWorkDetails($id)
    {
        $application = ConsumerApplication::find($id);
        $application->work_address_line_1 = Input::get('address');
        $application->work_address_state = Input::get('state');
        $application->work_address_city = Input::get('city');
        $application->work_address_pincode = Input::get('pincode');
        $application->work_address_landmark = Input::get('landmark');
        $application->save();

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

    public function isCVPUploaded($id)
    {
        $data = ConsumerApplicationFiles::where('consumer_application_id', $id)->where('file_type', 'cpv')->first(['id']);
        return (isset($data->id)) ? true : false;
    }

    public function getCPVStatus($data, $status = false)
    {
        $status = isset($status['status']) ? $status['status'] : $this->isCVPUploaded($data->id);
        $application = $data->emi ? $data->emi : 0; //ApplicationEMICalculation::where('application_id', $data->id)->first(['upfront_from_customer']);
        if (isset($application->id)) {
            $amount = $data->approved_amount - $application->upfront_from_customer;
            return ($amount > 250000) ? ($status ? false : true) : false;
        }
        return false;
    }




    public function getMatchScores($data){

        $match_array = array('name','digio_name','pan_name','loan_amount','emi_date','emi_amount','processing_fee','advance_fee','roi','tenure','insurance_fee','p_address_system','digio_address','lender_name');
        $creditReport = CreditReport::where('application_id', $data['consumer_applications']->id)->where('applicant_type', 1)->first(['id','panValidation', 'panVendor','bureau']);
        $loan_agreement_data = DocumentDetails::where('application_id', $data['consumer_applications']->id)->where('doc_type','LOAN_AGREEMENT')->whereNull('deleted_at')->whereNotNull('json_data')->orderBy('created_at','desc')->first();
        if (isset($creditReport->id) && $creditReport->panValidation){
        $pan_name = "";
            if($creditReport->bureau == "experian"){
                $kycResult = wall_decrypt(json_decode($creditReport->panValidation));
                if($kycResult != null){
                    if(isset($kycResult->kycResult)){
                        $panVerification = $kycResult->kycResult;
                        if (isset($panVerification->firstName)) {
                            $pan_name .= $panVerification->firstName . " ";
                        }
                        if (isset($panVerification->middleName)) {
                            $pan_name .= $panVerification->middleName . " ";
                        }
                        if (isset($panVerification->lastName)) {
                            $pan_name .= $panVerification->lastName . " ";
                        }
                    }
                }else{
                    $panError = true;
                }

            }else if($creditReport->bureau == "equifax"){
                $panVerification = json_decode(str_replace('sch:', '', $creditReport->panValidation));
                if (isset($panVerification->firstName)) {
                    $pan_name .= $panVerification->firstName . " ";
                }
                if (isset($panVerification->middleName)) {
                    $pan_name .= $panVerification->middleName . " ";
                }
                if (isset($panVerification->lastName)) {
                    $pan_name .= $panVerification->lastName . " ";
                }
            }

            if(isset($panError)){
                $pan_name = "";
            }
        }

        $digio_name = "";
        $digio_address = "";
        $digio_kyc = KYCDetails::where('application_id', $data['consumer_applications']->id)->where('applicant_type', 1)->whereNotNull('response')->orderBy('id','desc')->first(['response','created_at']);
        if(isset($digio_kyc->response)){

            $validations = json_decode($digio_kyc->response);
            if(isset($validations) && count($validations) >= 1 && count($validations) != 0){
                foreach($validations as $validation){
                    if (!isset($validation->actions)) {
                        if($validation->document_type == "aadhaar"){
                            $digio_name = $validation->name;
                            $digio_address = $validation->permanent_address;
                        }else if($validation->document_type == "pan"){
                            $digio_name = $validation->name;
                        }
                    } else {
                        foreach($validation->actions as $actions) {
                            if ($actions->action_ref == 'id_proof-1') {
                                $digio_name = isset($actions->id_card_data_response->name) ? $actions->id_card_data_response->name : '';
                            }
                            if ($actions->action_ref == 'digilocker-1') {
                                $digio_address = isset($actions->details->aadhaar->permanent_address) ? $actions->details->aadhaar->permanent_address : '';
                            }
                        }
                    }
                }
            }
        }

        $agreement_data = array();
        $agreement_data_decoded = isset($loan_agreement_data->json_data) && $loan_agreement_data->json_data ? json_decode($loan_agreement_data->json_data) : '';
        // dd($agreement_data_decoded);
        if(isset($loan_agreement_data->json_data) && $loan_agreement_data->json_data != null){

            $agreement_data['name'] = isset($agreement_data_decoded->name) ? $agreement_data_decoded->name : "";
            $agreement_data['loan_amount'] = isset($agreement_data_decoded->loan_amount) ? $agreement_data_decoded->loan_amount : "";
            $agreement_data['emi_date'] = isset($agreement_data_decoded->emi_date) ? date('Y-m-d',strtotime($agreement_data_decoded->emi_date)) : "";
            $agreement_data['emi_amount'] = isset($agreement_data_decoded->emi_amount) ? $agreement_data_decoded->emi_amount : "";
            $agreement_data['processing_fee'] = isset($agreement_data_decoded->processing_fee) ? $agreement_data_decoded->processing_fee : "";
            $agreement_data['roi'] = isset($agreement_data_decoded->rate_of_interest) ? $agreement_data_decoded->rate_of_interest : "";
            $agreement_data['tenure'] = isset($agreement_data_decoded->tenure) ? $agreement_data_decoded->tenure : "";
            $agreement_data['advance_fee'] = isset($agreement_data_decoded->advance_amount) ? $agreement_data_decoded->advance_amount : "";
            $agreement_data['insurance_fee'] = isset($agreement_data_decoded->insurance_fee) ? $agreement_data_decoded->insurance_fee : "";
            $agreement_data['p_address_system'] = isset($agreement_data_decoded->permanent_address) ? $agreement_data_decoded->permanent_address : "";
            $agreement_data['lender_name'] = isset($agreement_data_decoded->lender_name) ? $agreement_data_decoded->lender_name : "";
            $agreement_data['pan_name'] = isset($agreement_data_decoded->name) ? $agreement_data_decoded->name : "";
            $agreement_data['digio_address'] = isset($agreement_data_decoded->permanent_address) ? $agreement_data_decoded->permanent_address : "";
            $agreement_data['digio_name'] = isset($agreement_data_decoded->name) ? $agreement_data_decoded->name : "";

        }

        $system_data = array();

        $system_data['name'] = isset($data['consumer_applications']->name) ? $data['consumer_applications']->name : "";
        $system_data['loan_amount'] = isset($data['consumer_applications']->approved_amount) ? $data['consumer_applications']->approved_amount : "";
        $system_data['emi_date'] = isset($data['consumer_applications']->emi->emi_date) ? date('Y-m-d',strtotime($data['consumer_applications']->emi->emi_date)): "";
        $system_data['emi_amount'] = isset($data['consumer_applications']->emi->emi) ? $data['consumer_applications']->emi->emi : "";
        $system_data['processing_fee'] = isset($data['consumer_applications']->emi->processing_fee) ? $data['consumer_applications']->emi->processing_fee : "";
        $system_data['roi'] = isset($data['consumer_applications']->emi->interest_rate) ? $data['consumer_applications']->emi->interest_rate : "";
        $system_data['tenure'] = isset($data['consumer_applications']->emi->tenure) ? $data['consumer_applications']->emi->tenure : "";
        $system_data['advance_fee'] = isset($data['consumer_applications']->emi->upfront_from_customer) ? $data['consumer_applications']->emi->upfront_from_customer : "";
        $system_data['insurance_fee'] = isset($data['consumer_applications']->proFormaInvoice->insurance_premium_amount) ? $data['consumer_applications']->proFormaInvoice->insurance_premium_amount : "";
        $perm_address_line1 = isset($data['consumer_applications']->permanent_address_line_1) ? $data['consumer_applications']->permanent_address_line_1 : "";
        $perm_address_city = isset($data['consumer_applications']->permanent_address_city) ? $data['consumer_applications']->permanent_address_city : "";
        $perm_address_landmark = isset($data['consumer_applications']->permanent_address_landmark) ? $data['consumer_applications']->permanent_address_landmark : "";
        $perm_address_state = isset($data['consumer_applications']->permanent_address_state) ? $data['consumer_applications']->permanent_address_state : "";
        $perm_address_pincode = isset($data['consumer_applications']->permanent_address_pincode) ? $data['consumer_applications']->permanent_address_pincode : "";

        $system_data['p_address_system'] = $perm_address_line1." ".$perm_address_landmark." ".$perm_address_state." ".$perm_address_city." ".$perm_address_pincode;
        $system_data['lender_name'] = isset($data['consumer_applications']->lender->name) ? $data['consumer_applications']->lender->name : "";
        $system_data['pan_name'] = isset($pan_name) ? $pan_name : "";
        $system_data['digio_name'] = isset($digio_name) ? $digio_name : "";
        $system_data['digio_address'] = isset($digio_address) ? $digio_address : "";
        $resp = array();

        foreach($match_array as $match){
            $value1 = "";
            $value2 = "";
            $percent = "";
            $matching = "";
            if ($match == "roi" || $match == "advance_fee" || $match == "emi_amount" || $match == "processing_fee" || $match == "tenure" || $match == "loan_amount"){
                $value1 = isset($system_data[$match]) ? $system_data[$match] : '';
                $value2 = isset($agreement_data[$match]) ? $agreement_data[$match] : '';
                $matching = similar_text($value1, $value2, $percent);
            }elseif($match == "insurance_fee"){
                $insurance_applicable = isset($data['consumer_applications']->proFormaInvoice->insurance_premium_applicable) ? $data['consumer_applications']->proFormaInvoice->insurance_premium_applicable : 0;
                if($insurance_applicable == 0){
                    continue;
                }else{
                    $value1 = isset($system_data[$match]) && $system_data[$match] ? strtolower($system_data[$match]) : '';
                    $value2 = isset($agreement_data[$match]) && $agreement_data[$match] ? strtolower($agreement_data[$match]) : '';
                    $matching = similar_text($value1, $value2, $percent);
                }
            }elseif($match == "p_address_system"){
                $value1 = isset($system_data[$match]) && $system_data[$match] ? strtolower($system_data[$match]) : '';
                $modifiedString = strip_tags($value1);
                $modifiedString = str_replace(' ', '', $modifiedString);

                $value2 = isset($agreement_data[$match]) && $agreement_data[$match] ? strtolower($agreement_data[$match]) : '';
                $modifiedString2 = strip_tags($value2);
                $modifiedString2 = str_replace(' ', '', $modifiedString2);

                $matching = similar_text($modifiedString, $modifiedString2, $percent);
            }else{
                $value1 = isset($system_data[$match]) && $system_data[$match] ? strtolower($system_data[$match]) : '';
                $value2 = isset($agreement_data[$match]) && $agreement_data[$match] ? strtolower($agreement_data[$match]) : '';
                $matching = similar_text($value1, $value2, $percent);
            }
            $resp[$match]['check'] = round($percent);

        }
        $resp['location']['check'] = "false";

        $lat = isset($agreement_data_decoded->applicant_location_latitude) ? $agreement_data_decoded->applicant_location_latitude : "";
        $lng = isset($agreement_data_decoded->applicant_location_longitude) ? $agreement_data_decoded->applicant_location_longitude : "";

        if($lat != "" && $lng != ""){
            $checkInIndia = $this->isPointInIndia($lat,$lng);
            $resp['location']['check'] = $checkInIndia ;
            if ($checkInIndia == "true") {
                $agreement_data['location'] = 'Inside India';
            }else{
                $agreement_data['location'] = 'Outside India';
            }

        }else{
            $agreement_data['location'] = 'Not found';
        }

        $now =  Carbon::now();

        $resp['DiffDaysApp']['check'] = "false";

        $signingDate = isset($agreement_data_decoded->applicant_signed_date) ? $agreement_data_decoded->applicant_signed_date : "";
        $system_data['location'] = 'India';
        $system_data['DiffDaysApp'] = "";
        $agreement_data['DiffDaysApp'] = "";

        if($signingDate != "") {
            $App_date_signed = Carbon::parse($signingDate);
            $diff_days_app = $now->diffInDays($App_date_signed);
            if ($diff_days_app < 90) {
                $resp['DiffDaysApp']['check'] = "true";

            }
            $agreement_data['DiffDaysApp'] = $diff_days_app;
            $system_data['DiffDaysApp'] = "";
        }
        if($data['consumer_applications']->co_applicant_name != null){

        $resp['DiffDaysCoApp']['check'] = "false";
        $Coapp_signingDate = isset($agreement_data_decoded->co_applicant_signed_date) ? $agreement_data_decoded->co_applicant_signed_date : "";
        if($Coapp_signingDate != ""){
            $CoApp_date_signed = Carbon::parse($Coapp_signingDate);
            $diff_days_coapp = $now->diffInDays($CoApp_date_signed);

            if($diff_days_coapp < 90 ){
                $resp['DiffDaysCoApp']['check'] = "true";
            }
            $agreement_data['DiffDaysCoApp'] = $diff_days_coapp;
            $system_data['DiffDaysCoApp'] = "";
        }

        }
        $flag = true;
        foreach($resp as $key=>$value){
            if($key == 'digio_name' || $key == 'pan_name' || $key == 'digio_address'){
                if($value['check'] < 80){
                    $flag = false;
                }
            }else if($key == "location" || $key == 'DiffDaysApp' || $key == 'DiffDaysCoApp'){
                if($value['check'] != "true"){
                    $flag = false;
                }
            }else{
                if($value['check'] != 100){
                    $flag = false;
                }
            }
        }
        $resp['checkAllMatches']['check'] = $flag;

        $data['resp'] = $resp;
        $data['system_data'] = $system_data;
        $data['agreement_data'] = $agreement_data;
        // dd($resp);
        return $data;
    }

    public function isPointInIndia($lat, $lng)
    {
        // Define the bounding box coordinates for India
        $minLat = 6.747138;
        $maxLat = 35.674850;
        $minLng = 68.162385;
        $maxLng = 97.395561;

        // Check if the given lat and lng are within the bounding box
        if ($lat >= $minLat && $lat <= $maxLat && $lng >= $minLng && $lng <= $maxLng) {
            return 'true';
        } else {
            return 'false';
        }

    }

    public function verficationChecklist($id)
    {
        try{
            $isDigioDone = DigioVKYC::where('application_id', $id)
                ->where('applicant_type', 1) // Checking for primary applicant
                ->where('kyc_status', 'approved')
                ->where('kyc_journey', 'complete')
                ->exists();
            $data['sidebar'] = 'consumer-applications';
            $data['consumer_applications'] = ConsumerApplication::with('kycdetails','lender','proFormaInvoice', 'all_logger','logger','application_element', 'documents', 'creditReport', 'foir', 'user', 'mandate', 'Checklist', 'logs', 'bank_details', 'bank_details_multiple', 'co_applicant_logs.user', 'emi', 'products', 'merchant', 'category','disbursementOfferDisbursed')->where('id', $id)->first();        //echo "<pre>";print_r($data['consumer_applications']['application_element']->last_emi_date);exit;

            $pastLogs = $this->getPastLogs($data['consumer_applications']);
            $data['current_user'] = User::find($data['consumer_applications']->user_id);
            $docsList = [];
            $docsListIds = [];
            foreach ($data['consumer_applications']->documents as $document) {
                $docsList[$document->file_type] = $document->file_path;
            }
            // $docsList = [];
            foreach ($data['consumer_applications']->documents as $document) {
                $docsListIds[$document->file_type] = $document->id;
            }
            if(Input::has('credit_policy')){
                $verifications = $this->getNewVerificationList();
            }else {
                if($data['consumer_applications']->application_element->is_bnpl) {
                    $verifications = $this->getBNPLVerificationListV1();
                } else{
                    $verifications = $this->getVerificationListV1();
                }
            }
            $matchLists = $this->getMatchScores($data);
            $duplicateFieldStop = false;
            $productAtta= false;
            $appl_prod1 = explode(',', $data['consumer_applications']->application_element->product_name);
            $products1 = Products::whereIn('id', $appl_prod1)->get(['name']);
            foreach($products1 as $product){
                if((stripos($product->name,'atta') !==false) && (stripos($product->name,'chakki') !==false)){
                    $productAtta = true;
                }
            }
            //add required document layer
            if ($data['consumer_applications']->application_element && isset($data['consumer_applications']->application_element->mandatory_document_list) && !empty($data['consumer_applications']->application_element->mandatory_document_list)) {
                foreach (explode(',', $data['consumer_applications']->application_element->mandatory_document_list) as $mList) {

                    $vm_status = false;
                    $vm_value = '';
                    if (isset($docsList[$mList])) {
                        $vm_status = true;
                        $vm_value = $docsList[$mList];
                    }
                    if (!$vm_status && isset($docsList[str_replace('_', ' ', $mList)])) {
                        $vm_status = true;
                        $vm_value = $docsList[str_replace('_', ' ', $mList)];
                    }
                    if($mList == 'atta_chakki' && ($productAtta || (stripos($data['consumer_applications']->application_element->product_name,'atta') !== false && stripos($data['consumer_applications']->application_element->product_name,'chakki') !== false))){
                        $verifications[] = ['key' => $mList, 'name' => 'credit approval video(atta chakki)', 'status' => $vm_status, 'value' => $data['consumer_applications']->application_element->credit_approval_video ?? '', 'else' => 'text', 'group' => 'Mandatory Documents List'];
                        $duplicateFieldStop = true;
                    }elseif($mList != 'atta_chakki'){
                        $verifications[] = ['key' => $mList, 'name' => ucwords(str_replace('_', ' ', strtolower($mList))), 'status' => $vm_status, 'link' => 1, 'value' => $vm_value, 'type' => 'file', 'else' => 'file', 'group' => 'Mandatory Documents List'];
                    }
                }
            }
            if(!isset($data['consumer_applications']->application_element->credit_approval_video) && ($productAtta || (stripos($data['consumer_applications']->application_element->product_name,'atta') !== false && stripos($data['consumer_applications']->application_element->product_name,'chakki') !== false)) && !$duplicateFieldStop){
                $verifications[] = ['key' => 'atta_chakki', 'name' => 'credit approval video(atta chakki)', 'status' => true, 'value' => $data['consumer_applications']->application_element->credit_approval_video ?? '', 'else' => 'text', 'group' => 'Mandatory Documents List'];
            }

            $verifications = $this->getMultiStageProperties($id, $data['consumer_applications']->offer_id, $verifications);

            //end
            $data['documentPath'] = '';
            foreach ($verifications as $key => $verification) {
                if(Input::has('credit_policy') && $verification['key'] == 'blood_relative' && !$data['consumer_applications']->co_applicant_name){
                    unset($verifications[$key]);
                    continue;
                }
                if(($verification['key'] == 'co_app_digio_kyc' || $verification['key'] == 'co_app_onfido_kyc' /*||  $verification['key'] == 'co_app_hyperverge_kyc'*/) && !$data['consumer_applications']->co_applicant_name ){
                    unset($verifications[$key]);
                    continue;
                }
                if(Input::has('credit_policy') && $verification['key'] == 'salary' && $data['consumer_applications']->employee_status != 'SALARIED'){
                    unset($verifications[$key]);
                    continue;
                }
                $status = $this->getVerificationStatus($docsList, $data['consumer_applications'], $verification, $pastLogs);
                if(isset($status[2])){
                    $verifications[$key]['view'] = $status[2]['view'];
                }
                if ($status) {
                    $verifications[$key]['status'] = $status[1] ?? null;
                    $verifications[$key]['value'] = $status[0] ?? null;
                } else if ($verification['key'] == 'cpv' && in_array('approved', $pastLogs)) {
                    $verifications[$key]['required'] = $this->getCPVStatus($data['consumer_applications'], ['status' => $status]);
                } else if (($verification['key'] == 'designation' || $verification['key'] == 'department') && isset($pastLogs[count($pastLogs) - 1]) && $pastLogs[count($pastLogs) - 1] == 'approved') {
                    if (isset($data['consumer_applications']->employee_status) && $data['consumer_applications']->employee_status == 'SALARIED') {
                        $verifications[$key]['required'] = true;
                    }
                } else if ($verification['key'] == 'call_recording' && isset($pastLogs[count($pastLogs) - 1]) && $pastLogs[count($pastLogs) - 1] == 'approved') {
                    if (!$isDigioDone) {
                        $verifications[$key]['required'] = true;
                    }
                }
                if($verification['key'] == 'atta_chakki'){
                    $verifications[$key]['required'] = true;
                }

                //Mandate Amount Verification Checklist
                if($verification['key'] == 'mandate_status' || $verification['key'] == 'mandate_amount' || $verification['key'] == 'mandate_amount_exception_remarks'){
                        $mandateData = Mandate::where('consumer_application_id' ,$id)->whereIn('status' ,['active','submitted','registered'])->orderBy('created_at', 'desc')->first();
                    $consumerFiles = ConsumerApplicationFiles::where('consumer_application_id', $id)->wherenull('deleted_at')->where(function ($query) {
                        $query->where('file_type', 'like', '%nach%')
                        ->orWhere('file_type', 'like', '%mandate%')
                        ->orWhere('file_type', 'like', '%emandate%');
                    })->get();
                    //$verifications[$key]['status'] = !empty($mandateData) ? true : false;

                    if($verification['key'] == 'mandate_status'){
                        if (isset($consumerFiles) and count($consumerFiles) > 0) {
                            $verifications[$key]['value']  = 'Active';
                            $verifications[$key]['status'] = true;
                        }
                        if (isset($mandateData)) {
                            $verifications[$key]['value']  = !empty($mandateData) && in_array($mandateData->status, ['active','submitted','registered']) ? 'Active' : 'Inactive';
                            $verifications[$key]['status'] = !empty($mandateData) && in_array($mandateData->status, ['active','submitted','registered']) ? true : false;
                        }
                    }
                    else if($verification['key'] == 'mandate_amount'){
                        $verifications[$key]['value']  = !empty($mandateData) && $mandateData->mandate_amount > 0  ? $mandateData->mandate_amount : 0;
                        $netAmount = (new \App\Http\Controllers\NachController())->getNetAmountV1($data['consumer_applications']);
                        $verifications[$key]['system_value']  = $netAmount > 0 ? $netAmount : 0;
                        $verifications[$key]['status'] = !empty($mandateData) && $mandateData->mandate_amount == $netAmount ? true : false;
                    }
                    else if($verification['key'] == 'mandate_amount_exception_remarks'){
                        $exceptionRemarks1 = '';
                        if(!empty($mandateData)){
                            $amountException = ChecklistExceptionLogs::where('application_id',$id)->where('exception_type','mandate_amount_exception')->orderBy('created_at','desc')->first(['exception']);
                            if(!empty($amountException) && !empty($amountException->exception)){
                                $exceptionRemarks1 = $amountException->exception;
                            }
                        }
                        $verifications[$key]['value']  = $exceptionRemarks1;
                    }
                }

                //Mandate Document Verification Checklist
                if($verification['key'] == 'mandate_document' || $verification['key'] == 'mandate_utility_code' || $verification['key'] == 'mandate_creditor_name' || $verification['key'] == 'mandate_last_emi_date'){
                    $mandateDocs = DocumentDetails::where('application_id', $id)->where('doc_type', 'MANDATE')->whereNull('deleted_at')->orderBy('created_at','desc')->first();
                    // $verifications[$key]['status'] = !empty($mandateData) ? true : false;
                    if(!empty($mandateDocs)){
                        $mandateJsonData = json_decode($mandateDocs->json_data, true);
                        $mandateUtilityCode     = !empty($mandateJsonData['creditor_utility_code']) ? $mandateJsonData['creditor_utility_code'] : '';
                        $mandateCreditorName    = !empty($mandateJsonData['creditor_name']) ? $mandateJsonData['creditor_name'] : '';
                        $mandateLastEMIDate     = !empty($mandateJsonData['date_final_collection']) ? $mandateJsonData['date_final_collection'] : '';

                        if($verification['key'] == 'mandate_document'){
                            $document = ConsumerApplicationFiles::where('consumer_application_id', $id)->where('file_type', 'e mandate')->whereNull('deleted_at')->orderBy('created_at','desc')->first(['file_path']);
                            $documentPath = !empty($document->file_path) ? $document->file_path : '';
                            $verifications[$key]['value']  = $documentPath;
                            $verifications[$key]['status'] = !empty($documentPath) ? true : false;
                            $data['documentPath'] = $documentPath;
                        }
                        else if($verification['key'] == 'mandate_utility_code'){
                            $lenderBank = LenderBank::where('lender_id', $data['consumer_applications']['lender_id'])->orderBy('created_at', 'desc')->first(['utility_code']);
                            $utilityCode = !empty($lenderBank) ? $lenderBank->utility_code : '';
                            $verifications[$key]['value']  = $mandateUtilityCode;
                            $verifications[$key]['system_value']  = $utilityCode;
                            if(!empty($mandateUtilityCode) && !empty($utilityCode)){
                                $verifications[$key]['status'] = trim($mandateUtilityCode) == trim($utilityCode)  ? true : false;
                            }
                        }
                        else if($verification['key'] == 'mandate_creditor_name'){
                            $lender = Lenders::where('id', $data['consumer_applications']['lender_id'])->orderBy('created_at', 'desc')->first(['name']);
                            $creditorName = !empty($lender) ? $lender->name : '';
                            $verifications[$key]['value']  = $mandateCreditorName;
                            $verifications[$key]['system_value']  = $creditorName;
                            if(!empty($mandateCreditorName) && !empty($creditorName)){
                                $verifications[$key]['status'] = trim($mandateCreditorName) == trim($creditorName)  ? true : false;
                            }
                        }
                        else if($verification['key'] == 'mandate_last_emi_date'){
                            $lastEMIDate = '';
                            if(isset($data['consumer_applications']['application_element'])){
                                $lastEMIDate = $data['consumer_applications']['application_element']['last_emi_date'];
                            }
                            $verifications[$key]['system_value']  = $lastEMIDate;
                            $verifications[$key]['value']  = $mandateLastEMIDate;
                            $emiStatus = false;
                            if(!empty($mandateLastEMIDate) && !empty($lastEMIDate) && $mandateLastEMIDate > $lastEMIDate){
                                $emiStatus = true;
                            } else if($mandateLastEMIDate == ''){
                                $emiStatus = true;
                            }
                            $verifications[$key]['status'] = $emiStatus;
                        }
                    }
                }

                // Mandate miscllaneous - collection emi date check
                if($verification['key'] == 'mandate_misc_collection_date'){
                    $mandateData = Mandate::where('consumer_application_id' ,$id)->where('status','active')->orderBy('created_at', 'desc')->first();
                    if(!empty($mandateData) && $mandateData->status == 'active' && $mandateData->mandate_amount > 0){
                        $rawCollectionDate = $mandateData->date_first_collection;
                        $collection_date = Carbon::parse($rawCollectionDate)->format('Y-m-d H:i:s');
                        $emiCalc = ApplicationEMICalculation::where('application_id',$id)->first();
                        $rawEMIDate = !empty($emiCalc) ? $emiCalc->emi_date : '';
                        $emiDate = Carbon::parse($rawEMIDate)->format('Y-m-d H:i:s');
                        $verifications[$key]['status'] = !empty($collection_date) && !empty($emiDate) && $collection_date <= $emiDate ? true: false;
                        $verifications[$key]['value'] = substr($emiDate, 0, strrpos($emiDate, ' '));
                        $verifications[$key]['system_value'] = substr($collection_date, 0, strrpos($collection_date, ' '));
                    }
                }

                // Mandate miscllaneous - lender emi day check
                if($verification['key'] == 'mandate_misc_emi_day'){
                    $mandateData = Mandate::where('consumer_application_id' ,$id)->where('status','active')->orderBy('created_at', 'desc')->first();
                    if(!empty($mandateData) && $mandateData->status == 'active' && $mandateData->mandate_amount > 0){
                        $emiCalc = ApplicationEMICalculation::where('application_id',$id)->first();
                        $emiDate = !empty($emiCalc) ? $emiCalc->emi_date : '';
                        $lenderId = $data['consumer_applications']['lender_id'];
                        $lenderName = Lenders::where('id', $lenderId)->first();
                        $lenderEMIDetails = $this->checkLenderEMIDayV1($lenderId, $emiDate);
                        $verifications[$key]['status'] = !empty($lenderEMIDetails) && $lenderEMIDetails['status'] ? true : false;
                        $verifications[$key]['value'] = !empty($lenderEMIDetails) ? $lenderEMIDetails['day'].''.'th' : '';
                        $verifications[$key]['system_value'] = !empty($lenderName) ? $lenderName->name : '';
                    }
                }

                // Mandate document exception remark input
                if($verification['key'] == 'mandate_document_exception_remarks'){
                    $exceptionRemarks = '';
                    if(!empty($mandateData)){
                        $docException = ChecklistExceptionLogs::where('application_id',$id)->where('exception_type','mandate_document_exception')->orderby('created_at','desc')->first(['exception']);
                        if(!empty($docException) && !empty($docException->exception)){
                            $exceptionRemarks = $docException->exception;
                        }
                    }
                    $verifications[$key]['value']  = $exceptionRemarks;
                }
            }
            // dd($verifications);
            $applicant = ConsumerApplication::with('bank_details','document_details')->where('id',$id)->first();
            $checklistException = ChecklistExceptionLogs::where('application_id',$id)->where('exception_type','bank_exception')->orderby('created_at','desc')->first(['exception']);
            $exceptionRemarksForBank = null;
            if(!empty($checklistException) && !empty($checklistException->exception)){
                $exceptionRemarksForBank = $checklistException->exception;
            }

            $namePercentage = 0;
            $accountPercentage = 0;
            $ifscPercentage = 0;
            $nameBPercentage = 0;
            $accountBPercentage = 0;
            $ifscBPercentage = 0;
            $namePPercentage = 0;
            $accountPPercentage = 0;
            $ifscPPercentage = 0;
            $nameAPercentage = 0;
            $mname = null;
            $maccount = null;
            $mifsc = null;

            if(count($applicant->document_details) > 0){
                foreach($applicant->document_details as $documentInfo){
                    if($documentInfo->doc_type == 'MANDATE'){
                        $mapp = json_decode($documentInfo->json_data);
                        $mname = $mapp->debtor_account_name;
                        $maccount = $mapp->debtor_account_number;
                        $mifsc = $mapp->debtor_account_ifsc_code;
                    }
                }
            }

            if(isset($applicant->bank_details->karza_response)){
                $karza = json_decode($applicant->bank_details->karza_response);
                if(!empty($karza->result)){
                    $pname = $karza->result->accountName ?? null;
                    $paccount = $karza->result->accountNumber ?? null;
                    $pifsc = $karza->result->ifsc ?? null;
                }else{
                    $pname = null;
                    $paccount = null;
                    $pifsc = null;
                }
            }else{
                $pname = null;
                $paccount = null;
                $pifsc = null;
            }

            $mandate = [
                'name' => $mname,
                'account_number' => $maccount,
                'ifsc' => $mifsc
            ];
            $bank = [
                'name' => $applicant->bank_details->name ?? null,
                'account_number' => $applicant->bank_details->account_number ?? null,
                'ifsc' => $applicant->bank_details->ifsc_code ?? null
            ];
            $peny = [
                'name' => $pname,
                'account_number' => $paccount,
                'ifsc' => $pifsc
            ];

            if($mandate['name'] != null && $mandate['account_number'] != null && $mandate['ifsc'] != null){
                similar_text(strtolower($mandate['name']),strtolower($bank['name']), $nameBPercentage);
                similar_text(strtolower($mandate['account_number']),strtolower($bank['account_number']), $accountBPercentage);
                similar_text(strtolower($mandate['ifsc']),strtolower($bank['ifsc']), $ifscBPercentage);

                similar_text(strtolower($mandate['name']),strtolower($peny['name']), $namePPercentage);
                similar_text(strtolower($mandate['account_number']),strtolower($peny['account_number']), $accountPPercentage);
                similar_text(strtolower($mandate['ifsc']),strtolower($peny['ifsc']), $ifscPPercentage);

                similar_text(strtolower($mandate['name']),strtolower($applicant->name), $nameAPercentage);

                if(round($namePPercentage) < 60){
                    $namePPercentage1 = 'false';
                }else{
                    $namePPercentage1 = 'true';
                }
                if(round($accountPPercentage) < 100){
                    $accountPPercentage1 = 'false';
                }else{
                    $accountPPercentage1 = 'true';
                }
                if(round($ifscPPercentage) < 80){
                    $ifscPPercentage1 = 'false';
                }else{
                    $ifscPPercentage1 = 'true';
                }
            }else{
                similar_text(strtolower($bank['name']),strtolower($peny['name']), $namePercentage);
                similar_text(strtolower($bank['account_number']),strtolower($peny['account_number']), $accountPercentage);
                similar_text(strtolower($bank['ifsc']),strtolower($peny['ifsc']), $ifscPercentage);
                similar_text(strtolower($bank['name']),strtolower($applicant->name), $nameAPercentage);
                if(round($namePercentage) < 60){
                    $namePPercentage1 = 'false';
                }else{
                    $namePPercentage1 = 'true';
                }
                if(round($accountPercentage) < 100){
                    $accountPPercentage1 = 'false';
                }else{
                    $accountPPercentage1 = 'true';
                }
                if(round($ifscPercentage) < 80){
                    $ifscPPercentage1 = 'false';
                }else{
                    $ifscPPercentage1 = 'true';
                }
            }

            if(round($nameBPercentage) < 60){
                $nameBPercentage1 = 'false';
            }else{
                $nameBPercentage1 = 'true';
            }
            if(round($accountBPercentage) < 100){
                $accountBPercentage1 = 'false';
            }else{
                $accountBPercentage1 = 'true';
            }
            if(round($ifscBPercentage) < 80){
                $ifscBPercentage1 = 'false';
            }else{
                $ifscBPercentage1 = 'true';
            }
            if(round($nameAPercentage) < 60){
                $nameAPercentage1 = 'false';
            }else{
                $nameAPercentage1 = 'true';
            }

            if($nameBPercentage1 == 'true' && $accountBPercentage1 == 'true' && $ifscBPercentage1 == 'true' && $namePPercentage1 == 'true' && $nameAPercentage1 == 'true' && $accountPPercentage1 == 'true' && $ifscPPercentage1 == 'true'){
                $totalBankMatchStatus = 'true';
            }else{
                $totalBankMatchStatus = 'false';
            }
            $appName = $applicant->name ?? null;

            $bankMandateMatch = [
                'mandate' => [
                    'mname' => $mname,
                    'bName' => $bank['name'].'_'.$nameBPercentage1,
                    'pName' => $peny['name'].'_'.$namePPercentage1,
                    'EName' => $appName.'_'.$nameAPercentage1
                    ],
                'bank' => [
                    'maccount' => $maccount,
                    'bAccount' => $bank['account_number'].'_'.$accountBPercentage1,
                    'pAccount' => $peny['account_number'].'_'.$accountPPercentage1,
                    'EName' => ''
                    ],
                'peny' => [
                    'mifsc' => $mifsc,
                    'bIfsc' => $bank['ifsc'].'_'.$ifscBPercentage1,
                    'pIfsc' => $peny['ifsc'].'_'.$ifscPPercentage1,
                    'EName' => '']
            ];

            $verifications[] = ['key' => 'bank_details', 'name'=>'Bank Details', 'status' => true, 'valueRemark' => $exceptionRemarksForBank, 'bankMandate' => $bankMandateMatch, 'totalBankMatch' => $totalBankMatchStatus , 'group' => 'Bank & Mandate Verification Checklist' , 'subCollapse' => true, 'newChecklist' => 'bnk'];

            if($this->isInternal){
                return $verifications;
            }

            $exceptionList = [
                ['exceptionName'=>'CPV','exceptionStatus'=>false],['exceptionName'=>'repayment history','exceptionStatus'=>false],['exceptionName'=>'latest bureau','exceptionStatus'=>false],['exceptionName'=>'latest bank statement','exceptionStatus'=>false],['exceptionName'=>'CAM','exceptionStatus'=>false]
            ];
            $savedList = json_decode($data['consumer_applications']->application_element->multi_tranche_exception_list, true);
            if(isset($data['consumer_applications']->application_element->multi_tranche_exception_list)){
                foreach($savedList as $exceptionName){
                    foreach($exceptionList as $k => $list){
                        if($exceptionName['name'] == $list['exceptionName']){
                            unset($exceptionList[$k]);
                        }
                    }
                }
                foreach($savedList as $exceptionName){
                    array_push($exceptionList,['exceptionName'=>$exceptionName['name'],'exceptionStatus'=>$exceptionName['value']]);
                }
            }
            // rearrange the array
            $exceptionList = array_values($exceptionList);
            if(!Input::has('credit_policy')) {
                if(count($data['consumer_applications']->disbursementOfferDisbursed) && in_array($data['consumer_applications']->state,['disbursement checklist done','ready for disbursement','disbursed','nach registered']) && \Illuminate\Support\Facades\Session::has('Multi-disbursement_Exception_List|-57')){
                    $verifications[] = ['key' => 'multi_tranche', 'name'=>'Multi-Tranche Exception List', 'status' => true, 'value' => '', 'checkbox'=> false, 'excep-list' => $exceptionList, 'group' => 'Disbursement List For Multi-Tranche'];
                }
                $kyc_info = $this->getKYCInfo($data['consumer_applications']);
                foreach ($kyc_info as $kycName => $kycData) {
                    foreach ($kycData as $kyc) {
                        if(!is_array($kyc)){
                            $path_info = pathinfo($kyc);
                            if(isset($path_info['extension']) && $path_info['extension'] == 'pdf'){
                                $ext = "pdf";
                            }else{
                                $ext = "img";
                            }
                        }else{
                            $ext = "img";
                        }
                        $verifications[] = ['key' => $kycName, 'name' => ucwords(str_replace('_', ' ', strtolower($kycName))), 'status' => true, 'link' => 1, 'value' => $kyc, 'type' => $ext, 'else' => '', 'group' => 'Personal Verified'];
                    }
                }

                // $addressData = $this->getAddressMappedDocument($data['consumer_applications']);
                // foreach ($addressData as $addressKey => $addressItem) {
                //     $verifications[] = ['key' => $addressKey, 'name' => ucwords(str_replace('_', ' ', strtolower($addressKey))), 'status' => true, 'link' => 1, 'value_drp' => $docsListIds, 'value' => $addressItem, 'type' => 'drp', 'else' => '', 'group' => 'Personal Verified'];
                // }

                // $matching = $this->matchAddress($data['consumer_applications']);
                // foreach($matching as $k=>$mA){
                //     $match[] = [$mA];
                // }
                // $verifications[] = ['key' => 'address_comparison', 'name'=>'Address Comparison', 'status' => true, 'value' => $match, 'type' => 'comparison', 'table' => '', 'group' => 'Personal Verified'];
            }

            $response = [];
            foreach ($verifications as $verification) {
                $response[$verification['group']][] = $verification;
            }

            if(Input::has('credit_policy')){
                unset($response['Mandatory Documents List']);
            }

            // Product verification
            if($data['consumer_applications']->application_element && !empty($data['consumer_applications']->application_element->product_name) &&
                $data['consumer_applications']->products && count($data['consumer_applications']->products) > 0){
                $appl_prod = explode(',', $data['consumer_applications']->application_element->product_name);
                $products = Products::whereIn('id', $appl_prod)->get();
                $data['product_details'] = $products;
                $amount = 0;
                foreach($products as $product){
                    $amount += $product->amount;
                }
                if($amount >= $data['consumer_applications']['loan_amount'] || $amount == 0){
                    $data['product_verified'] = true;
                }else{
                    $data['product_verified'] = false;
                }
            }

            $miscChecklistStatus = $amountCheckStatus = true;
            $miscKeys = ['mandate_amount','mandate_status','mandate_document','mandate_utility_code','mandate_creditor_name','mandate_last_emi_date','mandate_misc_collection_date','mandate_misc_emi_day'];
            foreach($response as $group => $verificationList){
                if($group == 'Bank & Mandate Verification Checklist'){
                    foreach($verificationList as $verification){
                        if($verification['key'] == 'mandate_amount' && $verification['status'] == false){
                            $amountCheckStatus = false;
                        }
                        else if($verification['key'] != 'mandate_amount' && in_array($verification['key'], $miscKeys) && $verification['status'] == false){
                            $miscChecklistStatus = false;
                        }
                    }
                }
            }
            $data['amountCheckStatus'] = $amountCheckStatus;
            $data['miscChecklistStatus'] = $miscChecklistStatus;
            $data['totalBankMatchStatus'] = $totalBankMatchStatus;

            $data['verifications'] = $response;
            $data['processingFeeData'] = $this->getProcessingFeeData($id);
            $data['callLogs'] = CallLogs::where('_id', $id)->where('id_type', 'application_id')->whereNotNull('recording')->where('recording', '!=', '')->get(['id', 'to', 'from', 'direction', 'created_at', 'recording', 'purpose']);
            $data['verification_call_recording'] = CallLogs::where('_id', $id)->where('id_type', 'application_id')->where('purpose', 'verification_call')
                ->where(function ($query){
                $query->whereIn('status',['in-progress','completed']);
                })->orderBy('status','asc')->first(['id', 'to', 'from', 'direction', 'created_at', 'recording', 'purpose','status']);
            // $data['previous_loans'] = (new PreviousLoans(new Request(['id' => $id]), new AccountingController()))->getPreviousLoans();

            if (in_array('waiting for decision', $pastLogs)) {
                $data['hide_ready_for_decision'] = 1;
            }
            $data['button_pending'] = "Ready For Decision";
            $data['button_approve'] = "Approved";
            $data['button_reject'] = "Disapproved";

            // for disbursement checklist done
            if (in_array('approved', $pastLogs)) {
                $data['button_pending'] = "Ready For Disbursement";
                $data['button_approve'] = "Disbursed";
                $data['button_reject'] = "Disbursement Rejected";
                unset($data['hide_ready_for_decision']);
                if (in_array('disbursement checklist done', $pastLogs)) {
                    $data['hide_ready_for_decision'] = 1;
                }
            }

            /*if(in_array('Disbursement checklist done',$pastLogs)){
                $data['button_pending'] = "Ready For Decision";
                $data['button_approve'] = "Approved";
                $data['button_reject'] = "Disapproved";
                $data['hide_ready_for_decision'] = 1;
            }*/

            /*if($data['consumer_applications']->approved_amount < 75000){
                if(!in_array('approved',$pastLogs)) {
                    $data['showButtons'] = 1;
                }
            }*/
            $data['negativeProfile'] = NegativeProfile::get();
            $ArrayBack = $this->getArrayBackValidate($data['consumer_applications']->state);
            $data['show_disbursed'] = (in_array('approved', $ArrayBack)) ? 1 : 0;
            $data['application_id'] = $id;
            $data['state_list'] = StateModel::get(['name', 'code', 'id']);

            if (isset($data['consumer_applications']->co_applicant_name)) {
                $data['industries'] = ScoreCard::$industryCreditFair;
                $data['profession'] = ScoreCard::$professionTypeCreditFair;
            }

            if (Input::has('ref') && Input::get('ref') == 'verification') {
                $data['ref_verification'] = Input::get('ref');
            }

            $dataLists = $this->getUnapprovedPincodes($id);
            if($dataLists['unapproved_pin_codes'] && !isset($dataLists['approver_data_exist']->id) && Input::get('state') != 'waiting for decision'){
                if(isset($data['ref_verification'])) {
                    unset($data['ref_verification']);
                }
            }

            $data['consumer_applications']['courier'] = (new CouriersController(new Request()))->getCourier($id, 2);

            $grade = new GradeController(new Request());
            if ($data['consumer_applications']->state == 'waiting for decision' && (Auth::user()->user_type > 4)) {
                $_grade = $grade->ApprovalCheck($id);
                if ($_grade) {
                    $data['showButtons'] = 1;
                }
            }
            // if ($negativeArea = $this->getNegativeAreaList($data)) {
            //     $data['isNegativeArea'] = $negativeArea;
            // }

            $data['status_permission'] = $this->getPermissions();
            $data['advisors'] = User::where('user_type', '>=', 5)->whereNull('deleted_at')->get(['id', 'name']);
            $data['previous_status'] = StatusLogs::where('application_id', $id)->orderBy('created_at', 'desc')->first(['status']);

            // User Locations Start
            $data['isUserGeo'] = $this->getUserGeoLocationsData($data['consumer_applications']);
            $data['center_lat'] = '';
            $data['is_atta_chakki_case'] = (isset($data['consumer_applications']->application_element->type_of_customer) && $data['consumer_applications']->application_element->type_of_customer == $this->solar_category['atta_chakki']) ? true : false;
            $cpvGeoRecord = collect($data["isUserGeo"])->firstWhere('service', 'Cpv');

            if($cpvGeoRecord && isset($cpvGeoRecord["lat"]) && $data['is_atta_chakki_case']){
                $request = new Request([
                    'application_id' => $data['consumer_applications']->id,
                    'distance_in_km' => 5,
                ]);
                $cases_location = $this->getCaseWiseData($request);
                $current_address = [
                    'latitude' => $cpvGeoRecord["lat"],
                    'longitude' => $cpvGeoRecord["lng"],
                    'application_id' => 'this'
                ];
                $cases_location[] = $current_address;
                $data['cases_location'] = $cases_location;
            }

            $lats = [];
            $stops = [];
            foreach ($data['isUserGeo'] as $m_index => $location) {
                $lats[] = [
                    'lat' => (float)$location['lat'],
                    'lng' => (float)$location['lng'],
                    'date' => $location['distance_type']
                ];
                if (!$data['center_lat']) {
                    $data['center_lat'] = $location['lat'];
                    $data['center_lng'] = $location['lng'];
                }
                if (isset($data['isUserGeo'][$m_index])) {
                    $stops[] = ['origin' => ['lat' => $location['lat'], 'lng' => $location['lng']],
                        'destination' => ['lat' => $data['isUserGeo'][$m_index]['lat'], 'lng' => $data['isUserGeo'][$m_index]['lng']],
                        'distance' => $location['distance'], 'speed_mpm' => 0, 'date' => $location['distance_type']];
                }
            }
            //Corona
            $data['hotspotted_area'] = 0;
            if(isset($data['consumer_applications']->current_address_pincode) && !empty($data['consumer_applications']->current_address_pincode)){
                $is_hotspot = CoronaHotspot::where('pincode', $data['consumer_applications']->current_address_pincode)->first(['id']);
            }else{
                $is_hotspot = CoronaHotspot::where('pincode', $data['consumer_applications']->permanent_address_pincode)->first(['id']);
            }

            if(isset($is_hotspot->id) && !empty($is_hotspot->id)) {
                $data['hotspotted_area'] = 1;
            }

            $data['locations'] = $lats ?? '';
            $data['stops'] = $stops ?? '';
            // User Locations End

            $data['signing_doc'] = $this->getSignDocuments($data['consumer_applications']);
            $unapproved_pin_codes = $this->getUnapprovedPincodes($id);
            $data['upc'] = $unapproved_pin_codes['unapproved_pin_codes'];
            $data['upa'] = $unapproved_pin_codes['full_approved_address'];
            if(Auth::user()){
                $userData =  User::find(Auth::user()->id);
                if(isset($userData->is_manager) && $userData->is_manager == 1){
                    $data['isManager'] = $userData->is_manager;
                }
            }
            $data['approver_data_exist'] = $unapproved_pin_codes['approver_data_exist'];
            $data['unapproved_pin_codes'] = $unapproved_pin_codes['unapproved_pin_codes'];

            $approverData = ApproverData::with('user')->where('application_id',$id)->first();
            $data['approver_name']= ($approverData && $approverData->user) ? $approverData->user->name : '';
            $epfData = (new EPFUANLookup())->getUANByApplication($id);
            $data['epf'] = $epfData['epf'];
            $data['epfCoApplicant'] = $epfData['epfCoApplicant'];
            $userGeolocation = UserGeolocation::where('_id', $id)->where('id_type','application_id')->whereNotNull('longitude')->whereNotNull('latitude')->where('service','esign')->whereNull('deleted_at')->first(['id','longitude','latitude']);
            if(isset($userGeolocation->id) && $userGeolocation->longitude && $userGeolocation->latitude){
                $dataView = $this->getPincodeData(['pincode' => null, 'longitude' => $userGeolocation->longitude, 'latitude' => $userGeolocation->latitude], true);
                if (isset($dataView->results)) {
                    foreach ($dataView->results as $result) {
                        if ($result->address_components) {
                            foreach($result->address_components as $address_components){
                                if(isset($address_components->short_name) && $address_components->short_name != 'IN' && in_array('country',$address_components->types)) {
                                    $data['outside_location'] = 1;
                                    break;
                                }
                            }
                        }
                        if(isset($data['outside_location'])){
                            break;
                        }
                    }
                }
            }

            $digio = KYCDetails::where('application_id', $id)->whereNotNull('response')->orderBy('id','desc')->get(['response', 'applicant_type','created_at']);
            foreach($digio as $kyc){
                if($kyc['applicant_type'] == 2){
                    $data['co_app_digio_kyc'] = $kyc;
                }else{
                    $data['digio_kyc'] = $kyc;
                }
            }

            if(self::VKYC_VENDOR == "karza") {
                $customerData = KarzaVideoAttribute::where('application_id', $id)->whereNull('deleted_at')->whereIn('applicant_type', [1, 2])->get(['id', 'applicant_type']);
                foreach($customerData as $customer) {
                    // $customer_webhook = KarzaVideoWebhook::where('karza_id', $customer['id'])->get(['data', 'applicant_type']);
                    $customer_webhook = KarzaVideoWebhook::where('karza_id', $customer['id'])->get();
                    if($customer['applicant_type'] == 1) {
                        foreach($customer_webhook as $key => $value) {
                            $kyc_data = json_decode($value->data);
                            if (isset($kyc_data->actionLog) && $kyc_data->callSuccess && !isset($kyc_data->failureReason)) {
                                $key = array_search("agent", array_column(json_decode(json_encode($kyc_data->actionLog),TRUE), 'role'));
                                if($key) {
                                    $kyc_data->agentId = $kyc_data->actionLog[$key]->agentName;
                                }
                                $kyc_data->status = $kyc_data->approvedByAgent ?? '';
                                $data['customer_webhook'] = $kyc_data;
                            }
                            // $kyc_data->status = $kyc_data->approvedByAgent ?? '';
                            // $data['customer_webhook'] = $kyc_data;
                        }
                    }
                    if($customer['applicant_type'] == 2) {
                        foreach($customer_webhook as $key => $value) {
                            $kyc_data = json_decode($value->data);
                            if (isset($kyc_data->actionLog) && $kyc_data->callSuccess && !isset($kyc_data->failureReason)) {
                                $key = array_search("agent", array_column(json_decode(json_encode($kyc_data->actionLog),TRUE), 'role'));
                                if($key) {
                                    $kyc_data->agentId = $kyc_data->actionLog[$key]->agentName;
                                }
                                $kyc_data->status = $kyc_data->approvedByAgent ?? '';
                                $data['co_customer_webhook'] = $kyc_data;
                            }
                            // $kyc_data->status = $kyc_data->approvedByAgent ?? '';
                            // $data['co_customer_webhook'] = $kyc_data;
                        }
                    }
                }
            }else {
                $customerData = HypervergeVideoAttribute::where('application_id', $id)->whereIn('applicant_type', [1, 2])->get(['id']);
                foreach($customerData as $customer) {
                    $customer_webhook = HypervergeWebhook::where('hyper_id', $$customer['id'])->get(['data', 'applicant_type']);
                    if($customer['applicant_type'] == 1) {
                        foreach($customer_webhook as $key => $value) {
                            $kyc_data = json_decode($value->data);
                            if(isset($kyc_data->event_type) && $kyc_data->event_type == 'vcip_kyc_status'){
                                $data['customer_webhook'] = $kyc_data;
                            }
                        }
                    }
                    if($customer['applicant_type'] == 2) {
                        foreach($customer_webhook as $key => $value) {
                            $kyc_data = json_decode($value->data);
                            if(isset($kyc_data->event_type) && $kyc_data->event_type == 'vcip_kyc_status'){
                                $data['co_customer_webhook'] = $kyc_data;
                            }
                        }
                    }
                }
            }


            $data['matchlist'] = !empty($matchLists) ? $matchLists['resp'] : [];
            $data['system_data'] = !empty($matchLists) ? $matchLists['system_data'] : [];
            $data['agreement_data'] = !empty($matchLists) ? $matchLists['agreement_data'] : [];

            $data['vkyc_vendor'] = self::VKYC_VENDOR;
            $data['mandatory_document_logs'] = MandatoryDocumentListLogs::with('user')->where('application_id', $id)->orderBy('created_at', 'asc')->get(['id','mandatory_document_list', 'created_at','user_id']);
            $cwFactory = new CloudWatchLoggerFactory();
            $cwFactory->logger(json_encode(["application_id" => $id, "title" => "checklistdata", "response" =>$data]));
            return view('admin.consumer-application.verification_checklist_v1', $data);
        } catch (\Exception $e){
            //return \response()->json(['status' => 'failed','error' => $e->getMessage().' '.$e->getFile().' '.$e->getLine()], 200);
            (new Slack(new Request(['title' => 'Verfication Checklist V1', 'fields' => ['error'=>$e->getMessage(),'line'=>$e->getLine(),'trace'=>$e->getTraceAsString(), 'application id' => $id]])))->send();
        }
}

    public function verficationChecklistV1($id)
    {

        $data['sidebar'] = 'consumer-applications';
        $data['consumer_applications'] = ConsumerApplication::with('logger','application_element', 'documents', 'creditReport', 'foir', 'user', 'mandate', 'Checklist', 'logs', 'bank_details', 'bank_details_multiple', 'co_applicant_logs.user', 'emi', 'products', 'merchant', 'category','disbursementOfferDisbursed')->where('id', $id)->first();
        $pastLogs = $this->getPastLogs($data['consumer_applications']);
        $data['current_user'] = User::find($data['consumer_applications']->user_id);
        $docsList = [];
        $docsListIds = [];
        foreach ($data['consumer_applications']->documents as $document) {
            $docsList[$document->file_type] = $document->file_path;
        }
        // $docsList = [];
        foreach ($data['consumer_applications']->documents as $document) {
            $docsListIds[$document->file_type] = $document->id;
        }
        if(Input::has('credit_policy')){
            $verifications = $this->getNewVerificationList();
        }else {
            if($data['consumer_applications']->application_element->is_bnpl) {
                $verifications = $this->getBNPLVerificationList();
            } else{
                $verifications = $this->getVerificationList();
            }
        }


        //add required document layer
        if ($data['consumer_applications']->application_element && isset($data['consumer_applications']->application_element->mandatory_document_list) && !empty($data['consumer_applications']->application_element->mandatory_document_list)) {
            foreach (explode(',', $data['consumer_applications']->application_element->mandatory_document_list) as $mList) {

                $vm_status = false;
                $vm_value = '';
                if (isset($docsList[$mList])) {
                    $vm_status = true;
                    $vm_value = $docsList[$mList];
                }
                if (!$vm_status && isset($docsList[str_replace('_', ' ', $mList)])) {
                    $vm_status = true;
                    $vm_value = $docsList[str_replace('_', ' ', $mList)];
                }

                $verifications[] = ['key' => $mList, 'name' => ucwords(str_replace('_', ' ', strtolower($mList))), 'status' => $vm_status, 'link' => 1, 'value' => $vm_value, 'type' => 'file', 'else' => 'file', 'group' => 'Mandatory Documents List'];
            }
        }
        //end
        foreach ($verifications as $key => $verification) {

            if(Input::has('credit_policy') && $verification['key'] == 'blood_relative' && !$data['consumer_applications']->co_applicant_name){
                unset($verifications[$key]);
                continue;
            }
            if(($verification['key'] == 'co_app_digio_kyc' || $verification['key'] == 'co_app_onfido_kyc' /*||  $verification['key'] == 'co_app_hyperverge_kyc'*/) && !$data['consumer_applications']->co_applicant_name ){
                unset($verifications[$key]);
                continue;
            }
            if(Input::has('credit_policy') && $verification['key'] == 'salary' && $data['consumer_applications']->employee_status != 'SALARIED'){
                unset($verifications[$key]);
                continue;
            }
            $status = $this->getVerificationStatus($docsList, $data['consumer_applications'], $verification, $pastLogs);

            if(isset($status[2])){
                $verifications[$key]['view'] = $status[2]['view'];
            }
            if ($status) {
                $verifications[$key]['status'] = $status[1] ?? null;
                $verifications[$key]['value'] = $status[0] ?? null;
            } else if ($verification['key'] == 'cpv' && in_array('approved', $pastLogs)) {
                $verifications[$key]['required'] = $this->getCPVStatus($data['consumer_applications'], ['status' => $status]);
            } else if (($verification['key'] == 'designation' || $verification['key'] == 'department') && isset($pastLogs[count($pastLogs) - 1]) && $pastLogs[count($pastLogs) - 1] == 'approved') {
                if (isset($data['consumer_applications']->employee_status) && $data['consumer_applications']->employee_status == 'SALARIED') {
                    $verifications[$key]['required'] = true;
                }
            } else if ($verification['key'] == 'call_recording' && isset($pastLogs[count($pastLogs) - 1]) && $pastLogs[count($pastLogs) - 1] == 'approved') {
                $verifications[$key]['required'] = true;
            }

        }
        if($this->isInternal){
            return $verifications;
        }

        $exceptionList = [
            ['exceptionName'=>'CPV','exceptionStatus'=>false],['exceptionName'=>'repayment history','exceptionStatus'=>false],['exceptionName'=>'latest bureau','exceptionStatus'=>false],['exceptionName'=>'latest bank statement','exceptionStatus'=>false],['exceptionName'=>'CAM','exceptionStatus'=>false]
        ];
        $savedList = json_decode($data['consumer_applications']->application_element->multi_tranche_exception_list, true);
        if(isset($data['consumer_applications']->application_element->multi_tranche_exception_list)){
            foreach($savedList as $exceptionName){
                foreach($exceptionList as $k => $list){
                    if($exceptionName['name'] == $list['exceptionName']){
                        unset($exceptionList[$k]);
                    }
                }
            }
            foreach($savedList as $exceptionName){
                array_push($exceptionList,['exceptionName'=>$exceptionName['name'],'exceptionStatus'=>$exceptionName['value']]);
            }

        }
        // rearrange the array
        $exceptionList = array_values($exceptionList);

        if(!Input::has('credit_policy')) {
            if(count($data['consumer_applications']->disbursementOfferDisbursed) && in_array($data['consumer_applications']->state,['disbursement checklist done','ready for disbursement','disbursed','nach registered']) && \Illuminate\Support\Facades\Session::has('Multi-disbursement_Exception_List|-57')){
                $verifications[] = ['key' => 'multi_tranche', 'name'=>'Multi-Tranche Exception List', 'status' => true, 'value' => '', 'checkbox'=> false, 'excep-list' => $exceptionList, 'group' => 'Disbursement List For Multi-Tranche'];
            }

            $kyc_info = $this->getKYCInfo($data['consumer_applications']);
            foreach ($kyc_info as $kycName => $kycData) {
                foreach ($kycData as $kyc) {
                    if(!is_array($kyc)){
                        $path_info = pathinfo($kyc);
                        if(isset($path_info['extension']) && $path_info['extension'] == 'pdf'){
                            $ext = "pdf";
                        }else{
                            $ext = "img";
                        }
                    }else{
                        $ext = "img";
                    }
                    $verifications[] = ['key' => $kycName, 'name' => ucwords(str_replace('_', ' ', strtolower($kycName))), 'status' => true, 'link' => 1, 'value' => $kyc, 'type' => $ext, 'else' => '', 'group' => 'Personal Verified'];
                }
            }

            $addressData = $this->getAddressMappedDocument($data['consumer_applications']);
            foreach ($addressData as $addressKey => $addressItem) {
                $verifications[] = ['key' => $addressKey, 'name' => ucwords(str_replace('_', ' ', strtolower($addressKey))), 'status' => true, 'link' => 1, 'value_drp' => $docsListIds, 'value' => $addressItem, 'type' => 'drp', 'else' => '', 'group' => 'Personal Verified'];
            }

            $matching = $this->matchAddress($data['consumer_applications']);
            foreach($matching as $k=>$mA){
                $match[] = [$mA];
            }
            $verifications[] = ['key' => 'address_comparison', 'name'=>'Address Comparison', 'status' => true, 'value' => $match, 'type' => 'comparison', 'table' => '', 'group' => 'Personal Verified'];
        }

        $response = [];
        foreach ($verifications as $verification) {
            $response[$verification['group']][] = $verification;
        }


        if(Input::has('credit_policy')){
            unset($response['Mandatory Documents List']);
        }


        // Product verification
        if($data['consumer_applications']->application_element && !empty($data['consumer_applications']->application_element->product_name) &&
            $data['consumer_applications']->products && count($data['consumer_applications']->products) > 0){
            $appl_prod = explode(',', $data['consumer_applications']->application_element->product_name);
            $products = Products::whereIn('id', $appl_prod)->get();
            $data['product_details'] = $products;
            $amount = 0;
            foreach($products as $product){
                $amount += $product->amount;
            }
            if($amount >= $data['consumer_applications']['loan_amount'] || $amount == 0){
                $data['product_verified'] = true;
            }else{
                $data['product_verified'] = false;
            }
        }

        $data['verifications'] = $response;
        $data['processingFeeData'] = $this->getProcessingFeeData($id);

        $data['callLogs'] = CallLogs::where('_id', $id)->where('id_type', 'application_id')->whereNotNull('recording')->where('recording', '!=', '')->get(['id', 'to', 'from', 'direction', 'created_at', 'recording', 'purpose']);
        $data['verification_call_recording'] = CallLogs::where('_id', $id)->where('id_type', 'application_id')->where('purpose', 'verification_call')
            ->where(function ($query){
            $query->whereIn('status',['in-progress','completed']);
            })->orderBy('status','asc')->first(['id', 'to', 'from', 'direction', 'created_at', 'recording', 'purpose','status']);

        $data['previous_loans'] = (new PreviousLoans(new Request(['id' => $id]), new AccountingController()))->getPreviousLoans();

        if (in_array('waiting for decision', $pastLogs)) {
            $data['hide_ready_for_decision'] = 1;
        }
        $data['button_pending'] = "Ready For Decision";
        $data['button_approve'] = "Approved";
        $data['button_reject'] = "Disapproved";


        // for disbursement checklist done
        if (in_array('approved', $pastLogs)) {
            $data['button_pending'] = "Ready For Disbursement";
            $data['button_approve'] = "Disbursed";
            $data['button_reject'] = "Disbursement Rejected";
            unset($data['hide_ready_for_decision']);
            if (in_array('disbursement checklist done', $pastLogs)) {
                $data['hide_ready_for_decision'] = 1;
            }
        }

        /*if(in_array('Disbursement checklist done',$pastLogs)){
            $data['button_pending'] = "Ready For Decision";
            $data['button_approve'] = "Approved";
            $data['button_reject'] = "Disapproved";
            $data['hide_ready_for_decision'] = 1;
        }*/

        /*if($data['consumer_applications']->approved_amount < 75000){
            if(!in_array('approved',$pastLogs)) {
                $data['showButtons'] = 1;
            }
        }*/
        $data['negativeProfile'] = NegativeProfile::get();
        $ArrayBack = $this->getArrayBackValidate($data['consumer_applications']->state);
        $data['show_disbursed'] = (in_array('approved', $ArrayBack)) ? 1 : 0;
        $data['application_id'] = $id;
        $data['state_list'] = StateModel::get(['name', 'code', 'id']);

        if (isset($data['consumer_applications']->co_applicant_name)) {
            $data['industries'] = ScoreCard::$industryCreditFair;
            $data['profession'] = ScoreCard::$professionTypeCreditFair;
        }

        if (Input::has('ref') && Input::get('ref') == 'verification') {
            $data['ref_verification'] = Input::get('ref');
        }

        $dataLists = $this->getUnapprovedPincodes($id);
        if($dataLists['unapproved_pin_codes'] && !isset($dataLists['approver_data_exist']->id) && Input::get('state') != 'waiting for decision'){
            if(isset($data['ref_verification'])) {
                unset($data['ref_verification']);
            }
        }

        $data['consumer_applications']['courier'] = (new CouriersController(new Request()))->getCourier($id, 2);

        $grade = new GradeController(new Request());
        if ($data['consumer_applications']->state == 'waiting for decision' && (Auth::user()->user_type > 4)) {
            $_grade = $grade->ApprovalCheck($id);
            if ($_grade) {
                $data['showButtons'] = 1;
            }
        }
        // if ($negativeArea = $this->getNegativeAreaList($data)) {
        //     $data['isNegativeArea'] = $negativeArea;
        // }

        $data['status_permission'] = $this->getPermissions();
        $data['advisors'] = User::where('user_type', '>=', 5)->whereNull('deleted_at')->get(['id', 'name']);
        $data['previous_status'] = StatusLogs::where('application_id', $id)->orderBy('created_at', 'desc')->first(['status']);

        // User Locations Start
        $data['isUserGeo'] = $this->getUserGeoLocationsData($data['consumer_applications']);


        $data['center_lat'] = '';
        $lats = [];
        $stops = [];

        foreach ($data['isUserGeo'] as $m_index => $location) {
            $lats[] = [
                'lat' => (float)$location['lat'],
                'lng' => (float)$location['lng'],
                'date' => $location['distance_type']
            ];

            if (!$data['center_lat']) {
                $data['center_lat'] = $location['lat'];
                $data['center_lng'] = $location['lng'];
            }
            if (isset($data['isUserGeo'][$m_index])) {
                $stops[] = ['origin' => ['lat' => $location['lat'], 'lng' => $location['lng']],
                    'destination' => ['lat' => $data['isUserGeo'][$m_index]['lat'], 'lng' => $data['isUserGeo'][$m_index]['lng']],
                    'distance' => $location['distance'], 'speed_mpm' => 0, 'date' => $location['distance_type']];
            }
        }
        //Corona
        $data['hotspotted_area'] = 0;
        if(isset($data['consumer_applications']->current_address_pincode) && !empty($data['consumer_applications']->current_address_pincode)){
            $is_hotspot = CoronaHotspot::where('pincode', $data['consumer_applications']->current_address_pincode)->first(['id']);
        }else{
            $is_hotspot = CoronaHotspot::where('pincode', $data['consumer_applications']->permanent_address_pincode)->first(['id']);
        }

        if(isset($is_hotspot->id) && !empty($is_hotspot->id)) {
            $data['hotspotted_area'] = 1;
        }

        $data['locations'] = $lats;
        $data['stops'] = $stops;
        // User Locations End

        $data['signing_doc'] = $this->getSignDocuments($data['consumer_applications']);
        $unapproved_pin_codes = $this->getUnapprovedPincodes($id);
        $data['upc'] = $unapproved_pin_codes['unapproved_pin_codes'];
        $data['upa'] = $unapproved_pin_codes['full_approved_address'];
        if(Auth::user()){
            $userData =  User::find(Auth::user()->id);
            if(isset($userData->is_manager) && $userData->is_manager == 1){
                $data['isManager'] = $userData->is_manager;
            }
        }
        $data['approver_data_exist'] = $unapproved_pin_codes['approver_data_exist'];
        $data['unapproved_pin_codes'] = $unapproved_pin_codes['unapproved_pin_codes'];

        $approverData = ApproverData::with('user')->where('application_id',$id)->first();
        $data['approver_name']= ($approverData && $approverData->user) ? $approverData->user->name : '';
        $epfData = (new EPFUANLookup())->getUANByApplication($id);
        $data['epf'] = $epfData['epf'];
        $data['epfCoApplicant'] = $epfData['epfCoApplicant'];
        $userGeolocation = UserGeolocation::where('_id', $id)->where('id_type','application_id')->whereNotNull('longitude')->whereNotNull('latitude')->where('service','esign')->whereNull('deleted_at')->first(['id','longitude','latitude']);
        if(isset($userGeolocation->id) && $userGeolocation->longitude && $userGeolocation->latitude){
            $dataView = $this->getPincodeData(['pincode' => null, 'longitude' => $userGeolocation->longitude, 'latitude' => $userGeolocation->latitude], true);
            if (isset($dataView->results)) {
                foreach ($dataView->results as $result) {
                    if ($result->address_components) {
                        foreach($result->address_components as $address_components){
                            if(isset($address_components->short_name) && $address_components->short_name != 'IN' && in_array('country',$address_components->types)) {
                                $data['outside_location'] = 1;
                                break;
                            }
                        }
                    }
                    if(isset($data['outside_location'])){
                        break;
                    }
                }
            }
        }


        $digio = KYCDetails::where('application_id', $id)->whereNotNull('response')->orderBy('id','desc')->get(['response', 'applicant_type','created_at']);
        foreach($digio as $kyc){
            if($kyc['applicant_type'] == 2){
                $data['co_app_digio_kyc'] = $kyc;
            }else{
                $data['digio_kyc'] = $kyc;
            }
        }

        if(self::VKYC_VENDOR == "karza") {
            $customerData = KarzaVideoAttribute::with([
                'webhook' => function($query){
                    return $query->select('id','data');
                }])->where('application_id', $id)->whereNull('deleted_at')->whereIn('applicant_type', [1, 2])->get(['id', 'applicant_type']);
            foreach($customerData as $customer) {
                $customer_webhook = $customer['webhook'];
                //$customer_webhook = KarzaVideoWebhook::where('karza_id', $customer['id'])->get(['data', 'applicant_type']);
                if($customer['applicant_type'] == 1) {
                    foreach($customer_webhook as $key => $value) {
                        $kyc_data = json_decode($value->data);
                        if (isset($kyc_data->actionLog)) {
                            $key = array_search("agent", array_column(json_decode(json_encode($kyc_data->actionLog),TRUE), 'role'));
                            if($key) {
                                $kyc_data->agentId = $kyc_data->actionLog[$key]->agentName;
                            }
                        }
                        $kyc_data->status = $kyc_data->approvedByAgent ?? '';

                        $data['customer_webhook'] = $kyc_data;
                    }
                }
                if($customer['applicant_type'] == 2) {
                    foreach($customer_webhook as $key => $value) {
                        $kyc_data = json_decode($value->data);
                        if (isset($kyc_data->actionLog)) {
                            $key = array_search("agent", array_column(json_decode(json_encode($kyc_data->actionLog),TRUE), 'role'));
                            if($key) {
                                $kyc_data->agentId = $kyc_data->actionLog[$key]->agentName;
                            }
                        }
                        $kyc_data->status = $kyc_data->approvedByAgent ?? '';
                        $data['co_customer_webhook'] = $kyc_data;
                    }
                }
            }
        }else {
            $customerData = HypervergeVideoAttribute::where('application_id', $id)->whereIn('applicant_type', [1, 2])->get(['id']);
            foreach($customerData as $customer) {
                $customer_webhook = HypervergeWebhook::where('hyper_id', $$customer['id'])->get(['data', 'applicant_type']);
                if($customer['applicant_type'] == 1) {
                    foreach($customer_webhook as $key => $value) {
                        $kyc_data = json_decode($value->data);
                        if(isset($kyc_data->event_type) && $kyc_data->event_type == 'vcip_kyc_status'){
                            $data['customer_webhook'] = $kyc_data;
                        }
                    }
                }
                if($customer['applicant_type'] == 2) {
                    foreach($customer_webhook as $key => $value) {
                        $kyc_data = json_decode($value->data);
                        if(isset($kyc_data->event_type) && $kyc_data->event_type == 'vcip_kyc_status'){
                            $data['co_customer_webhook'] = $kyc_data;
                        }
                    }
                }
            }
        }
        $data['vkyc_vendor'] = self::VKYC_VENDOR;

        $data['mandatory_document_logs'] = MandatoryDocumentListLogs::with('user')->where('application_id', $id)->orderBy('created_at', 'asc')->get(['id','mandatory_document_list', 'created_at','user_id']);

        return view('admin.consumer-application.verification_checklist', $data);
    }

    public function getMatchScores1($consumer_data,$docName){

        $match_array = array('name','digio_name','pan_name','loan_amount','emi_date','emi_amount','processing_fee','advance_fee','roi','tenure','insurance_fee','p_address_system','digio_address','lender_name');
        if($docName == 'disbursement_advice'){
            $match_array = array('name','loan_amount','emi_date','emi_amount','processing_fee','advance_fee','roi','tenure','insurance_fee','p_address_system','lender_name','product_name','mobile_number','applicant_email','liability_percent','advance_interest_charged','amount_of_advance_interest_charged','subvention','gst','sgst','igst','net_disbursement','account_holder_name','name_of_bank','branch','account_number','ifsc_code','merchant_sign');
        }else{
            $match_array = array('name','digio_name','pan_name','loan_amount','emi_date','emi_amount','processing_fee','advance_fee','roi','tenure','insurance_fee','p_address_system','digio_address','lender_name');
        }
        $creditReport = CreditReport::where('application_id', $consumer_data->id)->where('applicant_type', 1)->first(['id','panValidation', 'panVendor','bureau']);
        $loan_agreement_data = DocumentDetails::where('application_id', $consumer_data->id)->where('doc_type','LOAN_AGREEMENT')->whereNull('deleted_at')->whereNotNull('json_data')->orderBy('created_at','desc')->first();
        $da_letter_data = DocumentDetails::where('application_id', $consumer_data->id)->where('doc_type','DISBURSEMENT_ADVICE')->whereNull('deleted_at')->whereNotNull('json_data')->orderBy('created_at','desc')->first();
        $sanction_letter_data = DocumentDetails::where('application_id', $consumer_data->id)->where('doc_type','SANCTION_LETTER')->whereNull('deleted_at')->whereNotNull('json_data')->orderBy('created_at','desc')->first();

        if (isset($creditReport->id) && $creditReport->panValidation){
        $pan_name = "";
            if($creditReport->bureau == "experian"){
                $kycResult = wall_decrypt(json_decode($creditReport->panValidation));
                if($kycResult != null){
                    if(isset($kycResult->kycResult)){
                        $panVerification = $kycResult->kycResult;
                        if (isset($panVerification->firstName)) {
                            $pan_name .= $panVerification->firstName . " ";
                        }
                        if (isset($panVerification->middleName)) {
                            $pan_name .= $panVerification->middleName . " ";
                        }
                        if (isset($panVerification->lastName)) {
                            $pan_name .= $panVerification->lastName . " ";
                        }
                    }
                }else{
                    $panError = true;
                }

            }else if($creditReport->bureau == "equifax"){
                $panVerification = json_decode(str_replace('sch:', '', $creditReport->panValidation));
                if (isset($panVerification->firstName)) {
                    $pan_name .= $panVerification->firstName . " ";
                }
                if (isset($panVerification->middleName)) {
                    $pan_name .= $panVerification->middleName . " ";
                }
                if (isset($panVerification->lastName)) {
                    $pan_name .= $panVerification->lastName . " ";
                }
            }

            if(isset($panError)){
                $pan_name = "";
            }
        }

        $digio_name = "";
        $digio_address = "";
        $digio_kyc = KYCDetails::where('application_id', $consumer_data->id)->where('applicant_type', 1)->whereNotNull('response')->orderBy('id','desc')->first(['response','created_at']);
        if(isset($digio_kyc->response)){

            $validations = json_decode($digio_kyc->response);
            if(isset($validations) && count($validations) >= 1 && count($validations) != 0 && $validations[0]){
                foreach($validations as $validation){
                    if (!isset($validation->actions)) {
                        if($validation->document_type == "aadhaar"){
                            $digio_name = $validation->name;
                            $digio_address = $validation->permanent_address;
                        }else if($validation->document_type == "pan"){
                            $digio_name = $validation->name;
                        }
                    } else {
                        foreach($validation->actions as $actions) {
                            if ($actions->action_ref == 'id_proof-1') {
                                $digio_name = isset($actions->id_card_data_response->name) ? $actions->id_card_data_response->name : '';
                            }
                            if ($actions->action_ref == 'digilocker-1') {
                                $digio_address = isset($actions->details->aadhaar->permanent_address) ? $actions->details->aadhaar->permanent_address : '';
                            }
                        }
                    }
                }
            }
        }

        $agreement_data = array();
        $agreement_data = ['name'=>'','loan_amount'=>'','emi_date'=>'','emi_amount'=>'','processing_fee'=>'','roi'=>'','tenure'=>'','advance_fee'=>'','insurance_fee'=>'','p_address_system'=>'','lender_name'=>'','pan_name'=>'','digio_address'=>'','digio_name'=>''];
        $sanction_data = array();
        $sanction_data = ['name'=>'','loan_amount'=>'','emi_date'=>'','emi_amount'=>'','processing_fee'=>'','roi'=>'','tenure'=>'','advance_fee'=>'','insurance_fee'=>'','p_address_system'=>'','lender_name'=>'','pan_name'=>'','digio_address'=>'','digio_name'=>''];
        $da_data = array();
        $da_data = ['name'=>'','loan_amount'=>'','emi_date'=>'','emi_amount'=>'','processing_fee'=>'','roi'=>'','tenure'=>'','advance_fee'=>'','insurance_fee'=>'','p_address_system'=>'','lender_name'=>'','product_name'=>'','mobile_number'=>'','applicant_email'=>'','product_name'=>'','liability_percent'=>'','advance_interest_charged'=>'','amount_of_advance_interest_charged'=>'','subvention'=>'','gst'=>'','sgst'=>'','igst'=>'','net_disbursement'=>'','<b> merchant bank details</b>'=>'','account_holder_name'=>'','name_of_bank'=>'','branch'=>'','account_number'=>'','ifsc_code'=>'','merchant_sign'=>''];
        $agreement_data_decoded = isset($loan_agreement_data->json_data) && $loan_agreement_data->json_data ? json_decode($loan_agreement_data->json_data) : '';
        $sanction_data_decoded = isset($sanction_letter_data->json_data) && $sanction_letter_data->json_data ? json_decode($sanction_letter_data->json_data) : '';
        $da_data_decoded = isset($da_letter_data->json_data) && $da_letter_data->json_data ? json_decode($da_letter_data->json_data) : '';

        if(isset($loan_agreement_data->json_data) && $loan_agreement_data->json_data != null){

            $agreement_data['name'] = isset($agreement_data_decoded->name) ? $agreement_data_decoded->name : "";
            $agreement_data['loan_amount'] = isset($agreement_data_decoded->loan_amount) ? $agreement_data_decoded->loan_amount : "";
            $agreement_data['emi_date'] = isset($agreement_data_decoded->emi_date) ? date('Y-m-d',strtotime($agreement_data_decoded->emi_date)) : "";
            $agreement_data['emi_amount'] = isset($agreement_data_decoded->emi_amount) ? $agreement_data_decoded->emi_amount : "";
            $agreement_data['processing_fee'] = isset($agreement_data_decoded->processing_fee) ? $agreement_data_decoded->processing_fee : "";
            $agreement_data['roi'] = isset($agreement_data_decoded->rate_of_interest) ? $agreement_data_decoded->rate_of_interest : "";
            $agreement_data['tenure'] = isset($agreement_data_decoded->tenure) ? $agreement_data_decoded->tenure : "";
            $agreement_data['advance_fee'] = isset($agreement_data_decoded->advance_amount) ? $agreement_data_decoded->advance_amount : "";
            $agreement_data['insurance_fee'] = isset($agreement_data_decoded->insurance_fee) ? $agreement_data_decoded->insurance_fee : "";
            $agreement_data['p_address_system'] = isset($agreement_data_decoded->permanent_address) ? $agreement_data_decoded->permanent_address : "";
            $agreement_data['lender_name'] = isset($agreement_data_decoded->lender_name) ? $agreement_data_decoded->lender_name : "";
            $agreement_data['pan_name'] = isset($agreement_data_decoded->name) ? $agreement_data_decoded->name : "";
            $agreement_data['digio_address'] = isset($agreement_data_decoded->permanent_address) ? $agreement_data_decoded->permanent_address : "";
            $agreement_data['digio_name'] = isset($agreement_data_decoded->name) ? $agreement_data_decoded->name : "";

        }
        if(isset($sanction_letter_data->json_data) && $sanction_letter_data->json_data != null){
            $sanction_data['name'] = isset($sanction_data_decoded->name) ? $sanction_data_decoded->name : "";
            $sanction_data['loan_amount'] = isset($sanction_data_decoded->loan_amount) ? $sanction_data_decoded->loan_amount : "";
            $sanction_data['emi_date'] = isset($sanction_data_decoded->emi_date) ? date('Y-m-d',strtotime($sanction_data_decoded->emi_date)) : "";
            $sanction_data['emi_amount'] = isset($sanction_data_decoded->emi_amount) ? $sanction_data_decoded->emi_amount : "";
            $sanction_data['processing_fee'] = isset($sanction_data_decoded->processing_fee) ? $sanction_data_decoded->processing_fee : "";
            $sanction_data['roi'] = isset($sanction_data_decoded->rate_of_interest) ? $sanction_data_decoded->rate_of_interest : "";
            $sanction_data['tenure'] = isset($sanction_data_decoded->tenure) ? $sanction_data_decoded->tenure : "";
            $sanction_data['advance_fee'] = isset($sanction_data_decoded->advance_amount) ? $sanction_data_decoded->advance_amount : "";
            $sanction_data['insurance_fee'] = isset($sanction_data_decoded->insurance_fee) ? $sanction_data_decoded->insurance_fee : "";
            $sanction_data['p_address_system'] = isset($sanction_data_decoded->permanent_address) ? $sanction_data_decoded->permanent_address : "";
            $sanction_data['lender_name'] = isset($sanction_data_decoded->lender_name) ? $sanction_data_decoded->lender_name : "";
            $sanction_data['pan_name'] = isset($sanction_data_decoded->name) ? $sanction_data_decoded->name : "";
            $sanction_data['digio_address'] = isset($sanction_data_decoded->permanent_address) ? $sanction_data_decoded->permanent_address : "";
            $sanction_data['digio_name'] = isset($sanction_data_decoded->name) ? $sanction_data_decoded->name : "";
        }
        if(isset($da_letter_data->json_data) && $da_letter_data->json_data != null){
            $da_data['name'] = isset($da_data_decoded->name) ? $da_data_decoded->name : "";
            $da_data['loan_amount'] = isset($da_data_decoded->loan_amount) ? $da_data_decoded->loan_amount : "";
            $da_data['emi_date'] = isset($da_data_decoded->emi_date) ? date('Y-m-d',strtotime($da_data_decoded->emi_date)) : "";
            $da_data['emi_amount'] = isset($da_data_decoded->emi_amount) ? $da_data_decoded->emi_amount : "";
            $da_data['processing_fee'] = isset($da_data_decoded->processing_fee) ? $da_data_decoded->processing_fee : "";
            $da_data['roi'] = isset($da_data_decoded->rate_of_interest) ? $da_data_decoded->rate_of_interest : "";
            $da_data['tenure'] = isset($da_data_decoded->tenure) ? $da_data_decoded->tenure : "";
            $da_data['advance_fee'] = isset($da_data_decoded->advance_amount) ? $da_data_decoded->advance_amount : "";
            $da_data['insurance_fee'] = isset($da_data_decoded->insurance_fee) ? $da_data_decoded->insurance_fee : "";
            $da_data['p_address_system'] = isset($da_data_decoded->permanent_address) ? $da_data_decoded->permanent_address : "";
            $da_data['lender_name'] = isset($da_data_decoded->lender_name) ? $da_data_decoded->lender_name : "";
            $da_data['liability_percent'] = isset($da_data_decoded->liability) ? $da_data_decoded->liability : "";
            $da_data['advance_interest_charged'] = isset($da_data_decoded->advance_interest_charged) ? $da_data_decoded->advance_interest_charged : "";
            $da_data['amount_of_advance_interest_charged'] = isset($da_data_decoded->amount_of_advance_interest_charged) ? $da_data_decoded->amount_of_advance_interest_charged : "";
            $da_data['subvention'] = isset($da_data_decoded->subvention) ? $da_data_decoded->subvention : "";
            $da_data['gst'] = isset($da_data_decoded->gst) ? $da_data_decoded->gst : "";
            $da_data['sgst'] = isset($da_data_decoded->sgst) ? $da_data_decoded->sgst : "";
            $da_data['igst'] = isset($da_data_decoded->igst) ? $da_data_decoded->igst : "";
            $da_data['net_disbursement'] = isset($da_data_decoded->net_disbursement) ? $da_data_decoded->net_disbursement : "";
            $da_data['mobile_number'] = isset($da_data_decoded->mobile_number) ? $da_data_decoded->mobile_number : "";
            $da_data['applicant_email'] = isset($da_data_decoded->applicant_email) ? $da_data_decoded->applicant_email : "";
            $da_data['product_name'] = isset($da_data_decoded->product_name) ? $da_data_decoded->product_name : "";
            $da_data['account_holder_name'] = isset($da_data_decoded->account_holder_name) ? $da_data_decoded->account_holder_name : '';
            $da_data['name_of_bank'] = isset($da_data_decoded->name_of_bank) ? $da_data_decoded->name_of_bank : '';
            $da_data['branch'] = isset($da_data_decoded->branch) ? $da_data_decoded->branch : '';
            $da_data['account_number'] = isset($da_data_decoded->account_number) ? $da_data_decoded->account_number : '';
            $da_data['ifsc_code'] = isset($da_data_decoded->ifsc_code) ? $da_data_decoded->ifsc_code : '';
            $da_data['merchant_sign']="";
        }

        $system_data = array();

        $system_data['name'] = isset($consumer_data->name) ? $consumer_data->name : "";
        $system_data['loan_amount'] = isset($consumer_data->approved_amount) ? $consumer_data->approved_amount : "";
        $system_data['emi_date'] = isset($consumer_data->emi->emi_date) ? date('Y-m-d',strtotime($consumer_data->emi->emi_date)): "";
        $system_data['emi_amount'] = isset($consumer_data->emi->emi) ? $consumer_data->emi->emi : "";
        $system_data['processing_fee'] = isset($consumer_data->emi->processing_fee) ? $consumer_data->emi->processing_fee : "";
        $system_data['roi'] = isset($consumer_data->emi->interest_rate) ? $consumer_data->emi->interest_rate : "";
        $system_data['tenure'] = isset($consumer_data->emi->tenure) ? $consumer_data->emi->tenure : "";
        $system_data['advance_fee'] = isset($consumer_data->emi->upfront_from_customer) ? $consumer_data->emi->upfront_from_customer : "";
        $system_data['insurance_fee'] = isset($consumer_data->proFormaInvoice->insurance_premium_applicable) && $consumer_data->proFormaInvoice->insurance_premium_applicable == 1 ? $consumer_data->proFormaInvoice->insurance_premium_amount : 0;
        $perm_address_line1 = isset($consumer_data->permanent_address_line_1) ? $consumer_data->permanent_address_line_1 : "";
        $perm_address_city = isset($consumer_data->permanent_address_city) ? $consumer_data->permanent_address_city : "";
        $perm_address_landmark = isset($consumer_data->permanent_address_landmark) ? $consumer_data->permanent_address_landmark : "";
        $perm_address_state = isset($consumer_data->permanent_address_state) ? $consumer_data->permanent_address_state : "";
        $perm_address_pincode = isset($consumer_data->permanent_address_pincode) ? $consumer_data->permanent_address_pincode : "";

        $system_data['p_address_system'] = $perm_address_line1." ".$perm_address_landmark." ".$perm_address_state." ".$perm_address_city." ".$perm_address_pincode;
        $system_data['lender_name'] = isset($consumer_data->lender->name) ? $consumer_data->lender->name : "";
        if($docName == 'disbursement_advice'){
            $system_data['mobile_number'] = isset($consumer_data->mobile_number) ? $consumer_data->mobile_number : "";
            $system_data['applicant_email'] = isset($consumer_data->email) ? $consumer_data->email : "";
            $product_name = isset($consumer_data->application_element->product_name) && $consumer_data->application_element->product_name ? $consumer_data->application_element->product_name : '';
            $product_name = $this->getProductName($product_name);
            $system_data['product_name'] = $product_name ?? "";
            $system_data['liability_percent'] = isset($consumer_data->liability_log->liability_log) ? $consumer_data->liability_log->liability_log : "";
            $system_data['advance_interest_charged'] = isset($consumer_data->emi->subvention) ? $consumer_data->emi->subvention : "";
            $downpayment = 0;
            if($consumer_data->merchant->charge_subvention_remaining_amount){
                $downpayment = $consumer_data->emi->upfront_from_customer;
            }
            $subventionAmount = (($consumer_data->approved_amount - $downpayment) * $consumer_data->emi->subvention) / 100;
            // $subventionAmount = isset($details['user']['consumer_emi']['partial_subvention_amount']) ? $details['user']['consumer_emi']['partial_subvention_amount'] : $subventionAmount;
            $system_data['amount_of_advance_interest_charged'] = isset($subventionAmount) ? $subventionAmount : "";
            $system_data['subvention'] = isset($consumer_data->emi->subvention) ? $consumer_data->emi->subvention : "";
            $system_data['gst'] = isset($consumer_data->emi->subvention_cgst) ? $consumer_data->emi->subvention_cgst : "";
            $system_data['sgst'] = isset($consumer_data->emi->subvention_sgst) ? $consumer_data->emi->subvention_sgst : "";
            $system_data['igst'] = isset($consumer_data->emi->subvention_igst) ? $consumer_data->emi->subvention_igst : "";
            $disbursement_array = (new DisbursementController(request()))->getDisbursementAmount($consumer_data);
            $system_data['net_disbursement'] = isset($disbursement_array['net_disbursement']) ? $disbursement_array['net_disbursement'] : "";
            $system_data['<b> merchant bank details</b>'] = '';
            if(isset($consumer_data->application_element->center_id) && $consumer_data->application_element->center_id != 0){
                $system_data['account_holder_name'] = isset($consumer_data->application_element->merchant_center->account_holder_name) ? $consumer_data->application_element->merchant_center->account_holder_name : $consumer_data->merchant_bank_details->account_holder_name;
                $system_data['name_of_bank'] = isset($consumer_data->application_element->merchant_center->name_of_bank) ? $consumer_data->application_element->merchant_center->name_of_bank : $consumer_data->merchant_bank_details->name_of_bank;
                $system_data['branch'] = isset($consumer_data->application_element->merchant_center->branch) ? $consumer_data->application_element->merchant_center->branch : $consumer_data->merchant_bank_details->branch;
                $system_data['account_number'] = isset($consumer_data->application_element->merchant_center->account_number) ? $consumer_data->application_element->merchant_center->account_number : $consumer_data->merchant_bank_details->account_number;
                $system_data['ifsc_code'] = isset($consumer_data->application_element->merchant_center->ifsc_code) ? $consumer_data->application_element->merchant_center->ifsc_code : $consumer_data->merchant_bank_details->ifsc_code;
                $system_data['merchant_sign'] = "";
            }else{
                $system_data['account_holder_name'] = isset($consumer_data->merchant_bank_details->account_holder_name) ? $consumer_data->merchant_bank_details->account_holder_name : '';
                $system_data['name_of_bank'] = isset($consumer_data->merchant_bank_details->name_of_bank) ? $consumer_data->merchant_bank_details->name_of_bank : '';
                $system_data['branch'] = isset($consumer_data->merchant_bank_details->branch) ? $consumer_data->merchant_bank_details->branch : '';
                $system_data['account_number'] = isset($consumer_data->merchant_bank_details->account_number) ? $consumer_data->merchant_bank_details->account_number : '';
                $system_data['ifsc_code'] = isset($consumer_data->merchant_bank_details->ifsc_code) ? $consumer_data->merchant_bank_details->ifsc_code : '';
                $system_data['merchant_sign'] = "";
            }
        }else{
            $system_data['pan_name'] = isset($pan_name) ? $pan_name : "";
            $system_data['digio_name'] = isset($digio_name) ? $digio_name : "";
            $system_data['digio_address'] = isset($digio_address) ? $digio_address : "";
        }

        $resp = array();
        $documentCheck = array();

        foreach($match_array as $match){
            $value1 = "";
            $value2 = "";
            $percent = "";
            $matching = "";
            if ($match == "roi" || $match == "advance_fee" || $match == "emi_amount" || $match == "processing_fee" || $match == "tenure" || $match == "loan_amount"){
                $value1 = isset($system_data[$match]) ? $system_data[$match] : '';
                if($docName == 'disbursement_advice'){
                    $value2 = isset($da_data[$match]) ? $da_data[$match] : '';
                }elseif($docName == 'sanction_letter'){
                    $value2 = isset($sanction_data[$match]) ? $sanction_data[$match] : '';
                }else{
                    $value2 = isset($agreement_data[$match]) ? $agreement_data[$match] : '';
                }
                $matching = similar_text($value1, $value2, $percent);
            }elseif($match == "insurance_fee"){
                $insurance_applicable = isset($consumer_data->proFormaInvoice->insurance_premium_applicable) ? $consumer_data->proFormaInvoice->insurance_premium_applicable : 0;
                if($insurance_applicable == 0){
                    continue;
                }else{
                    $value1 = isset($system_data[$match]) && $system_data[$match] ? strtolower($system_data[$match]) : '';
                    if($docName == 'disbursement_advice'){
                        $value2 = isset($da_data[$match]) && $da_data[$match] ? strtolower($da_data[$match]) : '';
                    }elseif($docName == 'sanction_letter'){
                        $value2 = isset($sanction_data[$match]) && $sanction_data[$match] ? strtolower($sanction_data[$match]) : '';
                    }else{
                        $value2 = isset($agreement_data[$match]) && $agreement_data[$match] ? strtolower($agreement_data[$match]) : '';
                    }
                    $matching = similar_text($value1, $value2, $percent);
                }
            }elseif($match == "p_address_system"){
                $value1 = isset($system_data[$match]) && $system_data[$match] ? strtolower($system_data[$match]) : '';
                $modifiedString = strip_tags($value1);
                $modifiedString = str_replace(' ', '', $modifiedString);

                if($docName == 'disbursement_advice'){
                    $value2 = isset($da_data[$match]) && $da_data[$match] ? strtolower($da_data[$match]) : '';
                }elseif($docName == 'sanction_letter'){
                    $value2 = isset($sanction_data[$match]) && $sanction_data[$match] ? strtolower($sanction_data[$match]) : '';
                }else{
                    $value2 = isset($agreement_data[$match]) && $agreement_data[$match] ? strtolower($agreement_data[$match]) : '';
                }
                $modifiedString2 = strip_tags($value2);
                $modifiedString2 = str_replace(' ', '', $modifiedString2);

                $matching = similar_text($modifiedString, $modifiedString2, $percent);
            }else{
                $value1 = isset($system_data[$match]) && $system_data[$match] ? strtolower($system_data[$match]) : '';
                if($docName == 'disbursement_advice'){
                    $value2 = isset($da_data[$match]) && $da_data[$match] ? strtolower($da_data[$match]) : '';
                }elseif($docName == 'sanction_letter'){
                    $value2 = isset($sanction_data[$match]) && $sanction_data[$match] ? strtolower($sanction_data[$match]) : '';
                }else{
                    $value2 = isset($agreement_data[$match]) && $agreement_data[$match] ? strtolower($agreement_data[$match]) : '';
                }
                $matching = similar_text($value1, $value2, $percent);
            }
            $resp[$match]['check'] = round($percent);
            if(in_array($match,['name','loan_amount','emi_date','emi_amount','processing_fee','roi','tenure','insurance_fee','advance_fee','p_address_system','lender_name'])){
                if(round($percent) == 100){
                    $documentCheck[$match]['status'] = '<i class="fa fa-check"></i>';
                }else{
                    $documentCheck[$match]['status'] = '<i class="fa fa-close" style="color:red"></i>';
                }
            }else{
                if(round($percent) >= 80){
                    $documentCheck[$match]['status'] = '<i class="fa fa-check"></i>';
                }else{
                    $documentCheck[$match]['status'] = '<i class="fa fa-close" style="color:red"></i>';
                }
            }

        }
        if($docName != 'disbursement_advice' && $docName != 'sanction_letter'){
            $resp['location']['check'] = "false";
            $documentCheck['location']['status'] = '<i class="fa fa-close" style="color:red"></i>';

            $lat = isset($agreement_data_decoded->applicant_location_latitude) ? $agreement_data_decoded->applicant_location_latitude : "";
            $lng = isset($agreement_data_decoded->applicant_location_longitude) ? $agreement_data_decoded->applicant_location_longitude : "";
            if($lat != "" && $lng != ""){
                $checkInIndia = $this->isPointInIndia($lat,$lng);
                $resp['location']['check'] = $checkInIndia ;
                if ($checkInIndia == "true") {
                    $agreement_data['location'] = 'Inside India';
                    $documentCheck['location']['status'] = '<i class="fa fa-check"></i>';
                }else{
                    $agreement_data['location'] = 'Outside India';
                    $documentCheck['location']['status'] = '<i class="fa fa-close" style="color:red"></i>';
                }
            }else{
                $agreement_data['location'] = 'Not found';
            }

            $now =  Carbon::now();

            $resp['DiffDaysApp']['check'] = "false";
            $documentCheck['DiffDaysApp']['status'] = '<i class="fa fa-close" style="color:red"></i>';

            $signingDate = isset($agreement_data_decoded->applicant_signed_date) ? $agreement_data_decoded->applicant_signed_date : "";
            $system_data['location'] = 'India';
            $system_data['DiffDaysApp'] = "";
            $agreement_data['DiffDaysApp'] = "";
            $sanction_data['location'] = '';

            if($signingDate != "") {
                $App_date_signed = Carbon::parse($signingDate);
                $diff_days_app = $now->diffInDays($App_date_signed);
                if ($diff_days_app < 90) {
                    $resp['DiffDaysApp']['check'] = "true";
                    $documentCheck['DiffDaysApp']['status'] = '<i class="fa fa-check"></i>';

                }
                $agreement_data['DiffDaysApp'] = $diff_days_app;
                $system_data['DiffDaysApp'] = "";
            }
            if($consumer_data->co_applicant_name != null){
                $system_data['DiffDaysCoApp'] = "";
                $agreement_data['DiffDaysCoApp'] = "";
                $resp['DiffDaysCoApp']['check'] = "false";
                $documentCheck['DiffDaysCoApp']['status'] = '<i class="fa fa-close" style="color:red"></i>';
                $Coapp_signingDate = isset($agreement_data_decoded->co_applicant_signed_date) ? $agreement_data_decoded->co_applicant_signed_date : "";
                if($Coapp_signingDate != ""){
                    $CoApp_date_signed = Carbon::parse($Coapp_signingDate);
                    $diff_days_coapp = $now->diffInDays($CoApp_date_signed);

                    if($diff_days_coapp < 90 ){
                        $resp['DiffDaysCoApp']['check'] = "true";
                        $documentCheck['DiffDaysCoApp']['status'] = '<i class="fa fa-check"></i>';
                    }
                    $agreement_data['DiffDaysCoApp'] = $diff_days_coapp;
                    $system_data['DiffDaysCoApp'] = "";
                }

            }
        }
        $flag = true;
        foreach($resp as $key=>$value){
            if($key == 'digio_name' || $key == 'pan_name' || $key == 'digio_address'){
                if($value['check'] < 80){
                    $flag = false;
                }
            }else if($key == "location" || $key == 'DiffDaysApp' || $key == 'DiffDaysCoApp'){
                if($value['check'] != "true"){
                    $flag = false;
                }
            }else{
                if($value['check'] != 100){
                    $flag = false;
                }
            }
        }
        $resp['checkAllMatches']['check'] = $flag;
        $verifiedData['checkAllMatches']['status'] = $flag ? '<i class="fa fa-check"></i>':'<i class="fa fa-close" style="color:red"></i>';

        if($docName == 'loan_agreement'){
            $verifiedData['system_data'] = $system_data;
            $verifiedData['agreement_data'] = $agreement_data;
        }elseif($docName == 'sanction_letter'){
            $verifiedData['system_data'] = $system_data;
            $verifiedData['sanction_data'] = $sanction_data;
        }elseif($docName == 'disbursement_advice'){
            $verifiedData['system_data'] = $system_data;
            $verifiedData['dA_data'] = $da_data;
        }
        // $verifiedData['status'] = $resp;
        $verifiedData['status'] = $documentCheck;
        return $verifiedData;

    }

    public function checklistStructure($data){
        return [$data['group_name'] => [
                $data['customer_type'] ?? 'applicant' => $data['field_display'] ?? 1,
                "group_status" => $data['group_display'] ?? 1,
                "group_info" => $data['group_misc_info'] ?? '',
                // "application_type_status" =>[
                //     $data['customer_type'] => $data['application_data_display'] ?? 1,
                // ],
                "section" =>[
                    $data['section_name'] ?? 'section_name' =>[
                        "section_info" => $data['section_misc_info'] ?? '',
                        $data['key'] ?? 'key_name' =>[
                        $data['customer_type'] ?? 'applicant' => [
                            "content" => [
                                    "name"=>$data["name"] ?? '',
                                    "key"=>$data["key"] ?? 'key_name',
                                    "key_1"=>$data["key_1"] ?? 'key_name_1',
                                    "key_2"=>$data["key_2"] ?? 'key_name_2',
                                    // "title"=>$data['tooltip_title'] ?? '',
                                    // below values should be either in array or string or numeric
                                    "value"=>$data["value"] ?? '',
                                    "value_1"=>$data["value_1"] ?? '',
                                    "value_2"=>$data["value_2"] ?? '',
                                    "default_error"=>$data['default_error'] ?? str_replace('_',' ',$data['key']).' is missing',
                                    "display_key_value" => 1,
                                    "multi_combine_table" => $data['multi_table'] ?? 0,
                                    "input_field"=>[
                                        "field_type"=>$data['field_type'] ?? '',
                                        "field_content"=>$data['field_content'] ?? '',
                                        "field_accessibility"=>$data['field_accessibility'] ?? '',
                                        "field_accessibility_1"=>$data['field_accessibility_1'] ?? '',
                                        "field_accessibility_2"=>$data['field_accessibility_2'] ?? '',
                                        "required"=>$data['field_required'] ?? 0,
                                        "required_1"=>$data['field_required_1'] ?? 0,
                                        "required_2"=>$data['field_required_2'] ?? 0,
                                        "accept_format"=>$data['field_accept_value'] ?? '',
                                        "placeholder"=>$data['field_placeholder'] ?? 'Enter '.str_replace('_',' ',$data["name"]).' here',
                                        "display_input_field"=>$data['field_display'] ?? 1,
                                        "default_value"=>$data['field_value'] ?? [],
                                        "default_value_1"=>$data['field_value_1'] ?? [],
                                        "default_value_2"=>$data['field_value_2'] ?? [],
                                        "default_misc"=>$data['field_misc'] ?? [],
                                        "class_attribute"=>"is_include_verification"
                                    ],
                                    "addition_field"=>[
                                        "additional_field_name"=>$data['additional_field_name'] ?? '',
                                        "additional_field_key"=>$data['additional_field_key'] ?? 'additional field key',
                                        "additional_field_type"=>$data['additional_field_type'] ?? 'input',
                                        "additional_field_display"=>$data['additional_field_display'] ?? 0,
                                        "additional_field_value"=>$data['additional_field_value'] ?? '',
                                        "additional_field_placeholder"=>$data['additional_field_placeholder'] ?? 'Enter '.str_replace('_',' ',$data['additional_field_name'] ?? ''). ' here'
                                    ],
                                    "checklist_page"=>$data['checklist_page'] ?? 'disbursement',
                                    "status"=>[
                                        "in"=>$data['status_in'] ?? '',
                                        "not_in"=>$data['status_not_in'] ?? ''
                                    ]
                                ],
                                "misc"=>$data['misc_content'] ?? []
                            ]
                        ],
                    ]
                ],
            ]
        ];
    }

    public function checklistPageData($id){
        $data = [];
        $data['sidebar'] = 'consumer-applications';
        $data['consumer_applications'] = ConsumerApplication::with('logger.user:id,name','application_element', 'documents', 'creditReport', 'foir', 'user', 'mandate', 'Checklist', 'logs', 'bank_details', 'bank_details_multiple', 'co_applicant_logs.user', 'emi', 'products', 'merchant', 'category','disbursementOfferDisbursed','totalCalls','lender.bank_details','liability_log')->where('id', $id)->first();
        if(!isset($data['consumer_applications']->id)){
            return redirect()->to('/admin/consumer-checklist-data/'.$id);
        }
        $data['checklistData'] = [];
        $pastLogs = $this->getPastLogs($data['consumer_applications']);

        $consumer_comparision_info[0] = $this->getMatchScores1($data['consumer_applications'],'loan_agreement');
        $group_misc_info = $consumer_comparision_info[0]['checkAllMatches'] ?? '';
        unset($consumer_comparision_info[0]['checkAllMatches']);
        $consumer_comparision_info1[0] = $this->getMatchScores1($data['consumer_applications'],'sanction_letter');
        $group_misc_info = $consumer_comparision_info1[0]['checkAllMatches'] ?? '';
        unset($consumer_comparision_info1[0]['checkAllMatches']);
        $consumer_comparision_info2[0] = $this->getMatchScores1($data['consumer_applications'],'disbursement_advice');
        $group_misc_info = $consumer_comparision_info2[0]['checkAllMatches'] ?? '';
        unset($consumer_comparision_info2[0]['checkAllMatches']);
        $docVerificationPermission = Session::has('Disbursements_View|2-5-0') ? true : false;
        $documentInfo = $this->generateCommonArray($consumer_comparision_info);
        $documentInfo1 = $this->generateCommonArray($consumer_comparision_info1);
        $documentInfo2 = $this->generateCommonArray($consumer_comparision_info2);

        $info['group_name'] = 'Document Details';
        $info['group_misc_info'] = $group_misc_info;
        $info['customer_type'] = 'applicant';
        // $info['group_display'] = 0;
        // $info['application_data_display'] = 0;
        $info['name'] = 'loan agreement';
        $info['key'] = 'loan_agreement';
        $info['value'] = $documentInfo ?? '';
        $info['value_1'] = $documentInfo1 ?? '';
        $info['value_2'] = $documentInfo2 ?? '';
        $info['field_type'] = 'other';
        $info['field_content'] = 'table2';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $info['misc_content'] = ['resp','system_data','agreement_data',"name", "loan_amount","emi_date","emi_amount","processing_fee","roi","tenure","advance_fee","insurance_fee","p_address_system","lender_name","pan_name","digio_name","digio_address","location","DiffDaysApp","check"];

        $checklistData23 = $this->checklistStructure($info);
        unset($info);

        $data['current_user'] = User::find($data['consumer_applications']->user_id);
        $data['previous_loans'] = (new PreviousLoans(new Request(['id' => $id]), new AccountingController()))->getPreviousLoans();
        $data['signing_doc'] = $this->getSignDocuments($data['consumer_applications']);
        $unapproved_pin_codes = $this->getUnapprovedPincodes($id);
        $data['upc'] = $unapproved_pin_codes['unapproved_pin_codes'];
        $data['upa'] = $unapproved_pin_codes['full_approved_address'];
        if(Auth::user()){
            $userData =  User::find(Auth::user()->id);
            if(isset($userData->is_manager) && $userData->is_manager == 1){
                $data['isManager'] = $userData->is_manager;
            }
        }
        $data['approver_data_exist'] = $unapproved_pin_codes['approver_data_exist'];
        $data['unapproved_pin_codes'] = $unapproved_pin_codes['unapproved_pin_codes'];

        if (in_array('waiting for decision', $pastLogs)) {
            $data['hide_ready_for_decision'] = 1;
        }
        $data['button_pending'] = "Ready For Decision";
        $data['button_approve'] = "Approved";
        $data['button_reject'] = "Disapproved";

        // for disbursement checklist done
        if (in_array('approved', $pastLogs)) {
            $data['button_pending'] = "Ready For Disbursement";
            $data['button_approve'] = "Disbursed";
            $data['button_reject'] = "Disbursement Rejected";
            unset($data['hide_ready_for_decision']);
            if (in_array('disbursement checklist done', $pastLogs)) {
                $data['hide_ready_for_decision'] = 1;
            }
        }

        $data['negativeProfile'] = NegativeProfile::get();
        $ArrayBack = $this->getArrayBackValidate($data['consumer_applications']->state);
        $data['show_disbursed'] = (in_array('approved', $ArrayBack)) ? 1 : 0;
        $data['application_id'] = $id;
        $data['state_list'] = StateModel::get(['name', 'code', 'id']);

        if (isset($data['consumer_applications']->co_applicant_name)) {
            $data['industries'] = ScoreCard::$industryCreditFair;
            $data['profession'] = ScoreCard::$professionTypeCreditFair;
        }

        $dataLists = $this->getUnapprovedPincodes($id);
        if($dataLists['unapproved_pin_codes'] && !isset($dataLists['approver_data_exist']->id) && Input::get('state') != 'waiting for decision'){
            if(isset($data['ref_verification'])) {
                unset($data['ref_verification']);
            }
        }

        $grade = new GradeController(new Request());
        if ($data['consumer_applications']->state == 'waiting for decision' && (Auth::user()->user_type > 4)) {
            $_grade = $grade->ApprovalCheck($id);
            if ($_grade) {
                $data['showButtons'] = 1;
            }
            // if (empty(array_filter($_grade->getOutput()))) {
            //     $data['showButtons'] = 1;
            // }
        }

        $data['status_permission'] = $this->getPermissions();
        $data['advisors'] = User::where('user_type', '>=', 5)->whereNull('deleted_at')->get(['id', 'name']);
        $data['previous_status'] = StatusLogs::where('application_id', $id)->orderBy('created_at', 'desc')->first(['status']);

        $digioVKYC = DigioVKYC::where('application_id', $id)->whereNull('deleted_at')->get()->keyBy('applicant_type');
        $isDigioCompleted = $isDigioCompletedCoapp = false;
        $applicant_digio = $digioVKYC->get(1);
        $co_applicant_digio = $digioVKYC->get(2);

        if(isset($applicant_digio->id)){
            if($applicant_digio->applicant_type == 1){
                if((isset($applicant_digio->kyc_status) && $applicant_digio->kyc_journey == "complete") && (isset($applicant_digio->kyc_status) && $applicant_digio->kyc_status == "approved")){
                    $isDigioCompleted = true;
                }
            }
        }
        if(isset($co_applicant_digio->id)){
            if($co_applicant_digio->applicant_type == 2){
                if((isset($co_applicant_digio->kyc_status) && $co_applicant_digio->kyc_journey == "complete") && (isset($co_applicant_digio->kyc_status) && $co_applicant_digio->kyc_status == "approved")){
                    $isDigioCompletedCoapp = true;
                }
            }
        }

        $userGeolocation = UserGeolocation::where('_id', $id)->where('id_type','application_id')->whereNotNull('longitude')->whereNotNull('latitude')->where('service','esign')->whereNull('deleted_at')->first(['id','longitude','latitude']);
        if(isset($userGeolocation->id) && $userGeolocation->longitude && $userGeolocation->latitude){
            $dataView = $this->getPincodeData(['pincode' => null, 'longitude' => $userGeolocation->longitude, 'latitude' => $userGeolocation->latitude], true);
            if (isset($dataView->results)) {
                foreach ($dataView->results as $result) {
                    if ($result->address_components) {
                        foreach($result->address_components as $address_components){
                            if(isset($address_components->short_name) && $address_components->short_name != 'IN' && in_array('country',$address_components->types)) {
                                $data['outside_location'] = 1;
                                break;
                            }
                        }
                    }
                    if(isset($data['outside_location'])){
                        break;
                    }
                }
            }
        }

        $karzaApproved = $CoKarzaApproved = false;
        // check if applicant has been approved
        if (self::VKYC_VENDOR == "karza") {
            $karzaApproved = self::checkKarzaApproved($id, 1);
        }

        // check if applicant has been approved
        if (self::VKYC_VENDOR == "karza") {
            $CoKarzaApproved = self::checkKarzaApproved($id, 2);
        }
        $documentList = $data['consumer_applications']->documents->toArray();
        // dd($documentList);
        $file_path = array();
        foreach($documentList as $index => $information){
            if(((stripos($information['file_type'],'merchant') !== false) && (stripos($information['file_type'],'confirmation') !== false)) || ((strpos($information['file_type'],'pro_forma_invoice') !== false) && (!empty($information['created_by']) && $information['created_by'] != 107) || (isset($information['doc_ref_id']) && $information['doc_ref_id'] == 'proforma by merchant')) || ($information['file_type']== 'proforma' && $information['created_by'] == null)){
                $file_path['merchant_confirmation'] = $information['file_path'] ?? '';
            }
            if((stripos($information['file_type'],'quotation') !== false) && ((stripos($information['file_type'],'bill') !== false) || (stripos($information['file_type'],'final') !== false)) || (strpos($information['file_type'],'proforma') !== false)){
                $file_path['quotation_bill'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'security_cheques') !== false){
                $file_path['security_cheques'] = $information['file_path'] ?? '';
            }
            if((strpos($information['file_type'],'nach_submitted_proof')) !== false || (stripos($information['file_type'],'nach') !== false) || (stripos($information['file_type'],'mandate') !== false)){
                $file_path['nach_submitted_proof'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'loan_agreement_esign') !== false){
                $file_path['loan_agreement_esign'] = $information['file_path'] ?? '';
            }
            if((strpos($information['file_type'],'pro_forma_invoice') !== false) && ((empty($information['created_by'])) || ($information['created_by'] == 107))){
                $file_path['da'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'sanction_letter') !== false){
                $file_path['sanction_letter'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'credit_appraisal_memo') !== false){
                $file_path['credit_appraisal_memo'] = $information['file_path'] ?? '';
            }
            if(stripos($information['file_type'],'hypothecation') !== false){
                $file_path['hypothecation_agreement'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'cpv') !== false){
                $file_path['cpv_report'] = $information['file_path'] ?? '';
            }
            if((strpos($information['file_type'],'advance_amount_receipt') !== false)){
                $file_path['advance_amount_receipt'] = $information['file_path'] ?? '';
            }
            if((strpos($information['file_type'],'tfr') !== false)){
                $file_path['tfr'] = $information['file_path'] ?? '';
            }
            if((strpos($information['file_type'],'solar_quotation') !== false)){
                $file_path['solar_quotation'] = $information['file_path'] ?? '';
            }
            if((strpos($information['file_type'],'proforma') !== false)){
                $file_path['proforma'] = $information['file_path'] ?? '';
            }
            // if(((stripos($information['file_type'],'atta') !== false) || (stripos($information['file_type'],'aata') !== false) || (stripos($information['file_type'],'aaata') !== false)) && (stripos($information['file_type'],'chakki') !== false) && (stripos($information['file_type'],'video') !== false || stripos($information['file_type'],'vedio') !== false)){
            //     $file_path['atta_chakki_video'] = $information['file_path'] ?? '';
            // }
            if(($information['file_type'] == 'reference') || (stripos($information['file_type'],'reference_1') !== false)){
                $file_path['reference_1'] = $information['file_path'] ?? '';
            }
            if($information['file_type'] == 'reference_2'){
                $file_path['reference_2'] = $information['file_path'] ?? '';
            }
            if((stripos($information['file_type'],'processing_fee_receipt') !== false)){
                $file_path['processing_fee_receipt'] = $information['file_path'] ?? '';
            }
            if(((strpos($information['file_type'],'panvalidation') !== false) || (strpos($information['file_type'],'pan validation') !== false)) && (stripos($information['file_type'],'co') === false)){
                $file_path['pan_validation'] = $information['file_path'] ?? '';
            }
            if(((stripos($information['file_type'],'co ') !== false) && (strpos($information['file_type'],'app') !== false) && (strpos($information['file_type'],'pan') !== false) && (strpos($information['file_type'],'validation') !== false)) || (stripos($information['file_type'],'co_applicant_pan_validation') !== false)){
                $file_path['co_pan_validation'] = $information['file_path'] ?? '';
            }

            if((strtolower($information['file_type']) == 'pan_card') || (strtolower($information['file_type']) == 'pan card')){
                $file_path['pan_card'] = $information['file_path'] ?? '';
            }
            if((strpos($information['file_type'],'co_applicant_pan_card') !== false) || (strpos($information['file_type'],'co-applicant_pan_card') !== false)){
                $file_path['co_pan_card'] = $information['file_path'] ?? '';
            }
            if((strtolower($information['file_type']) == 'aadhar_card')){
                $file_path['aadhar_card'] = $information['file_path'] ?? '';
            }
            // if((strpos($information['file_type'],'co applicant_aadhar_card') !== false) || (strpos($information['file_type'],'co-applicant_aadhar_card') !== false) || (strpos($information['file_type'],'co_applicant_aadhar_card') !== false)){
            //     $file_path['co_aadhar_card'] = $information['file_path'] ?? '';
            // }
            if(in_array($information['file_type'],['co applicant_aadhar_card','co-applicant_aadhar_card','co_applicant_aadhar_card'])){
                $file_path['co_aadhar_card'] = $information['file_path'] ?? '';
            }
            if((strtolower($information['file_type']) == 'aadhar_card_back')){
                $file_path['aadhar_card_back'] = $information['file_path'] ?? '';
            }
            if(in_array($information['file_type'],['co_applicant_aadhar_card_back', 'co-applicant_aadhar_card_back', 'co applicant_aadhar_card back', 'co applicant_aadhar_card_back'])){
                $file_path['co_aadhar_card_back'] = $information['file_path'] ?? '';
            }

            if((strtolower($information['file_type']) == 'self_attested_pan')){
                $file_path['self_attested_pan'] = $information['file_path'] ?? '';
            }
            // if(((stripos($information['file_type'],'co app') !== false) || (stripos($information['file_type'],'co_app') !== false)) && (stripos($information['file_type'],'self') !== false) && (stripos($information['file_type'],'pan') !== false)){
            //     $file_path['self_attested_co_pan'] = $information['file_path'] ?? '';
            // }

            if((strtolower($information['file_type']) == 'self_attested_co_pan') || (strtolower($information['file_type']) == 'co_app_self_attested_pan')){
                $file_path['self_attested_co_pan'] = $information['file_path'] ?? '';
            }
            if((strtolower($information['file_type']) == 'self_attested_aadhar')){
                $file_path['self_attested_aadhar'] = $information['file_path'] ?? '';
            }
            if((strtolower($information['file_type']) == 'self_attested_co_aadhar') || (strtolower($information['file_type']) == 'co_app_self_attested_aadhar')){
                $file_path['self_attested_co_aadhar'] = $information['file_path'] ?? '';
            }
            // if(((stripos($information['file_type'],'co app') !== false) || (stripos($information['file_type'],'co_app') !== false)) && (stripos($information['file_type'],'self') !== false) && ((stripos($information['file_type'],'aadhar') !== false) || (stripos($information['file_type'],'adhar') !== false))){
            //     $file_path['self_attested_co_aadhar'] = $information['file_path'] ?? '';
            // }
            if((strtolower($information['file_type']) == 'self_aadhar_card_back')){
                $file_path['self_aadhar_card_back'] = $information['file_path'] ?? '';
            }
            if((strtolower($information['file_type']) == 'self_attested_co_aadhar_back')){
                $file_path['self_attested_co_aadhar_back'] = $information['file_path'] ?? '';
            }
            if((strtolower($information['file_type']) == 'self_attested_selfie')){
                $file_path['self_attested_selfie'] = $information['file_path'] ?? '';
            }
            if((strtolower($information['file_type']) == 'self_attested_co_selfie')){
                $file_path['self_attested_co_selfie'] = $information['file_path'] ?? '';
            }
            // if(((stripos($information['file_type'],'co app') !== false) || (stripos($information['file_type'],'co_app') !== false)) && (stripos($information['file_type'],'self') !== false) && ((stripos($information['file_type'],'aadhar') !== false) || (stripos($information['file_type'],'adhar') !== false)) && (strpos($information['file_type'],'back') !== false)){
            //     $file_path['self_attested_co_aadhar_back'] = $information['file_path'] ?? '';
            // }
            if((strtolower($information['file_type']) == 'customer_photo') || (strtolower($information['file_type']) == 'customer_photo ') || (strtolower($information['file_type']) == 'customer photo') || (strtolower($information['file_type']) == 'customers photo') || (strtolower($information['file_type']) == 'customer\'s photo') || (stripos($information['file_type'],'customer selfie') !== false) || ($information['file_type'] == 'CUSTPHOTO_'.$id.'_1')){
                $file_path['customer_photo'] = $information['file_path'] ?? '';
            }
            if((strpos($information['file_type'],'co_applicant_customer_photo') !== false) || ((stripos($information['file_type'],'co ') !== false) && (strpos($information['file_type'],'app') !== false) && (strpos($information['file_type'],'customer') !== false) && (strpos($information['file_type'],'photo') !== false)) || ($information['file_type'] == 'CUSTPHOTO_'.$id.'_2')){
                $file_path['co_applicant_customer_photo'] = $information['file_path'] ?? '';
            }
            if((strpos($information['file_type'],'call_recording') !== false)){
                $file_path['call_recording'] = $information['file_path'] ?? '';
            }
            if((strpos($information['file_type'],'solar_installation_proof') !== false)){
                $file_path['solar_installation_proof'] = $information['file_path'] ?? '';
            }
            if($karzaApproved){
                if((strpos($information['file_type'],'karzaV_report_applicant') !== false)){
                    $file_path['karza_vkyc_report'] = $information['file_path'] ?? '';
                }
                if((strpos($information['file_type'],'vkyc_video_'.$id.'_1') !== false)){
                    $file_path['karza_vkyc_video'] = $information['file_path'] ?? '';
                }
            }
            if($CoKarzaApproved){
                if((strpos($information['file_type'],'karzaV_report_co_applicant') !== false)){
                    $file_path['co_karza_vkyc_report'] = $information['file_path'] ?? '';
                }
                if((strpos($information['file_type'],'vkyc_video_'.$id.'_2') !== false)){
                    $file_path['co_karza_vkyc_video'] = $information['file_path'] ?? '';
                }
            }
            if($isDigioCompleted){
                if((strpos($information['file_type'],'vkyc_report_'.$id.'_1') !== false)){
                    $file_path['digio_vkyc_report'] = $information['file_path'] ?? '';
                }
                if((strpos($information['file_type'],'vkyc_video_'.$id.'_1') !== false)){
                    $file_path['digio_vkyc_video'] = $information['file_path'] ?? '';
                }
            }

            if($isDigioCompletedCoapp){
                if((strpos($information['file_type'],'vkyc_report_'.$id.'_2') !== false)){
                    $file_path['co_digio_vkyc_report'] = $information['file_path'] ?? '';
                }
                if((strpos($information['file_type'],'vkyc_video_'.$id.'_2') !== false)){
                    $file_path['co_digio_vkyc_video'] = $information['file_path'] ?? '';
                }
            }
            if((strpos($information['file_type'],'e mandate') !== false)){
                $file_path['e_mandate'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'fd_receipt') !== false || strpos($information['file_type'],'FD Receipt') !== false || strpos($information['file_type'],'FD_Receipt') !== false){
                $file_path['fd_receipt'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'fd_lien_letter') !== false || strpos($information['file_type'],'FD_Lien_Letter') !== false){
                $file_path['fd_lien_letter'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'mnrega_job_card') !== false){
                $file_path['mnrega_job_card'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'letter_national_population_register') !== false){
                $file_path['letter_national_population_register'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'commissioning_certificate') !== false){
                $file_path['commissioning_certificate'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'sync_report') !== false){
                $file_path['sync_report'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'net_metering_agreement') !== false){
                $file_path['net_metering_agreement'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'rm_visit_checklist') !== false){
                $file_path['rm_visit_checklist'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'rm_visit_photo') !== false){
                $file_path['rm_visit_photo'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'installation_photo') !== false || strpos($information['file_type'],'Installation Photo') !== false){
                $file_path['installation_photo'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'electricity_bill') !== false){
                $file_path['electricity_bill'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'e_bill_validation') !== false){
                $file_path['e_bill_validation'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'work_completion_report') !== false){
                $file_path['work_completion_report'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'e_bill_with_solar_reading') !== false){
                $file_path['e_bill_with_solar_reading'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'chakki_running_on_panel_video') !== false){
                $file_path['chakki_running_on_panel_video'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'noc_for_solar_installation') !== false){
                $file_path['noc_for_solar_installation'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'tax_invoice') !== false || strpos($information['file_type'],'Tax Invoice') !== false){
                $file_path['tax_invoice'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'pg_agreement_1') !== false || strpos($information['file_type'],'PG agreement 1') !== false){
                $file_path['pg_agreement_1'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'pg_agreement_2') !== false || strpos($information['file_type'],'PG agreement 2') !== false){
                $file_path['pg_agreement_2'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'pg_agreement_3') !== false || strpos($information['file_type'],'PG agreement 3') !== false){
                $file_path['pg_agreement_3'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'pg_signed_kyc_document') !== false || strpos($information['file_type'],'PG signed KYC document') !== false){
                $file_path['pg_signed_kyc_document'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'affidavit_1') !== false || strpos($information['file_type'],'Affidavit 1') !== false){
                $file_path['affidavit_1'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'affidavit_2') !== false || strpos($information['file_type'],'Affidavit 2') !== false){
                $file_path['affidavit_2'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'registration_certificate') !== false || strpos($information['file_type'],'Registration Certificate') !== false){
                $file_path['registration_certificate'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'board_resolution') !== false || strpos($information['file_type'],'Board resolution') !== false){
                $file_path['board_resolution'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'incorporation_certificate') !== false || strpos($information['file_type'],'Incorporation Certificate') !== false){
                $file_path['incorporation_certificate'] = $information['file_path'] ?? '';
            }
            if(strtolower($information['file_type']) == 'moa' || strpos($information['file_type'],'MOA') !== false){
                $file_path['moa'] = $information['file_path'] ?? '';
            }
            if(strtolower($information['file_type']) == 'aoa' || strpos($information['file_type'],'AOA') !== false){
                $file_path['aoa'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'list_of_member') !== false || strpos($information['file_type'],'List of Member') !== false){
                $file_path['list_of_member'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'bye_law') !== false || strpos($information['file_type'],'Bye Law') !== false){
                $file_path['bye_law'] = $information['file_path'] ?? '';
            }
            if(strtolower($information['file_type']) == 'oc' || strpos($information['file_type'],'OC') !== false){
                $file_path['oc'] = $information['file_path'] ?? '';
            }
            if(strtolower($information['file_type']) == 'cc' || strpos($information['file_type'],'CC') !== false){
                $file_path['cc'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'trust_deed') !== false || strpos($information['file_type'],'Trust Deed') !== false){
                $file_path['trust_deed'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'partnership_deed') !== false || strpos($information['file_type'],'Partnership Deed') !== false){
                $file_path['partnership_deed'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'voter_id') !== false || strpos($information['file_type'],'Voter id') !== false){
                $file_path['voter_id'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'passport') !== false || strpos($information['file_type'],'Passport') !== false){
                $file_path['passport'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'visa_copy') !== false || strpos($information['file_type'],'Visa copy') !== false){
                $file_path['visa_copy'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'driving_license') !== false || strpos($information['file_type'],'Driving License') !== false){
                $file_path['driving_license'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'osv_mnrega_job_card') !== false || strpos($information['file_type'],'MNREGA_Job_Card') !== false){
                $file_path['mnrega_job_card'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'Letter_Issued_by_National_Population_register') !== false || strpos($information['file_type'],'Letter Issued by National Population register') !== false){
                $file_path['Letter_Issued_by_National_Population_register'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'pg_self_attested_aadhar_card_1') !== false || strpos($information['file_type'],'PG self attested Aadhar card 1') !== false){
                $file_path['pg_self_attested_aadhar_card_1'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'pg_self_attested_pan_card_1') !== false || strpos($information['file_type'],'PG self attested Pan card 1') !== false){
                $file_path['pg_self_attested_pan_card_1'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'pg_self_attested_aadhar_card_2') !== false || strpos($information['file_type'],'PG self attested Aadhar card 2') !== false){
                $file_path['pg_self_attested_aadhar_card_2'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'pg_self_attested_pan_card_2') !== false || strpos($information['file_type'],'PG self attested Pan card 2') !== false){
                $file_path['pg_self_attested_pan_card_2'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'pg_self_attested_aadhar_card_3') !== false || strpos($information['file_type'],'PG self attested Aadhar card 3') !== false){
                $file_path['pg_self_attested_aadhar_card_3'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'pg_self_attested_pan_card_3') !== false || strpos($information['file_type'],'PG self attested Pan card 3') !== false){
                $file_path['pg_self_attested_pan_card_3'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'owner_self_attested_pan_card_1') !== false || strpos($information['file_type'],'Owner self attested Pan card 1') !== false){
                $file_path['owner_self_attested_pan_card_1'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'owner_self_attested_aadhar_card_1') !== false || strpos($information['file_type'],'Owner self attested Aadhar card 1') !== false){
                $file_path['owner_self_attested_aadhar_card_1'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'self_attested_entity_pan_card') !== false || strpos($information['file_type'],'Self attested Entity PAN card') !== false){
                $file_path['self_attested_entity_pan_card'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'self_attested_auth_signatory_1_pan') !== false || strpos($information['file_type'],'Self attested Auth signatory 1 PAN') !== false){
                $file_path['self_attested_auth_signatory_1_pan'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'self_attested_auth_signatory_2_pan') !== false || strpos($information['file_type'],'Self attested Auth signatory 2 PAN') !== false){
                $file_path['self_attested_auth_signatory_2_pan'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'self_attested_auth_signatory_1_aadhaar') !== false || strpos($information['file_type'],'Self attested Auth signatory 1 Aadhaar') !== false){
                $file_path['self_attested_auth_signatory_1_aadhaar'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'self_attested_auth_signatory_2_aadhaar') !== false || strpos($information['file_type'],'Self attested Auth signatory 2 Aadhaar') !== false){
                $file_path['self_attested_auth_signatory_2_aadhaar'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'self_attested_director_1_pan') !== false || strpos($information['file_type'],'Self attested Director 1 PAN') !== false){
                $file_path['self_attested_director_1_pan'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'self_attested_director_2_pan') !== false || strpos($information['file_type'],'Self attested Director 2 PAN') !== false){
                $file_path['self_attested_director_2_pan'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'self_attested_director_3_pan') !== false || strpos($information['file_type'],'Self attested Director 3 PAN') !== false){
                $file_path['self_attested_director_3_pan'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'self_attested_director_1_aadhaar') !== false || strpos($information['file_type'],'Self attested Director 1 Aadhaar') !== false){
                $file_path['self_attested_director_1_aadhaar'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'self_attested_director_2_aadhaar') !== false || strpos($information['file_type'],'Self attested Director 2 Aadhaar') !== false){
                $file_path['self_attested_director_2_aadhaar'] = $information['file_path'] ?? '';
            }
            if(strpos($information['file_type'],'self_attested_director_3_aadhaar') !== false || strpos($information['file_type'],'Self attested Director 3 PAN') !== false){
                $file_path['self_attested_director_3_aadhaar'] = $information['file_path'] ?? '';
            }
        }
        $data['documentPath'] = $file_path['e_mandate'] ?? '';

        $info['group_name'] = 'disbursement checklist done';
        $info['customer_type'] = 'applicant';
        // $info['group_display'] = 0;
        // $info['application_data_display'] = 0;
        $info['name'] = 'complete signed nach form';
        $info['key'] = 'nach_submitted_proof';
        $info['value'] = $file_path['nach_submitted_proof'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'pdf';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData35 = $this->checklistStructure($info);
        unset($info);
        $info['group_name'] = 'disbursement checklist done';
        $info['customer_type'] = 'applicant';
        // $info['group_display'] = 0;
        // $info['application_data_display'] = 0;
        $info['name'] = 'sanction letter';
        $info['key'] = 'sanction_letter';
        $info['value'] = $file_path['sanction_letter'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'pdf';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData36 = $this->checklistStructure($info);
        unset($info);
        $info['group_name'] = 'disbursement checklist done';
        $info['customer_type'] = 'applicant';
        // $info['group_display'] = 0;
        // $info['application_data_display'] = 0;
        $info['name'] = 'undated or post dated cheques';
        $info['key'] = 'security_cheques';
        $info['value'] = $file_path['security_cheques'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'pdf';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData37 = $this->checklistStructure($info);
        unset($info);
        $info['group_name'] = 'disbursement checklist done';
        $info['customer_type'] = 'applicant';
        // $info['group_display'] = 0;
        // $info['application_data_display'] = 0;
        $info['name'] = 'signed loan agreement';
        $info['key'] = 'signed_loan_agreement';
        $info['value'] = $file_path['loan_agreement_esign'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'pdf';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData38 = $this->checklistStructure($info);
        unset($info);
        $info['group_name'] = 'disbursement checklist done';
        $info['customer_type'] = 'applicant';
        // $info['group_display'] = 0;
        // $info['application_data_display'] = 0;
        $info['name'] = 'hypothecation agreement';
        $info['key'] = 'hypothecation_agreement';
        $info['value'] = $file_path['hypothecation_agreement'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'pdf';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData39 = $this->checklistStructure($info);
        unset($info);
        $info['group_name'] = 'disbursement checklist done';
        $info['customer_type'] = 'applicant';
        // $info['group_display'] = 0;
        // $info['application_data_display'] = 0;
        $info['name'] = 'advance payment confirmation / down payment';
        $info['key'] = 'advance_amount_receipt';
        $info['value'] = $file_path['advance_amount_receipt'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'pdf';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = '';
        $info['field_accept_value'] = 'application/pdf, image/*';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData31 = $this->checklistStructure($info);
        $document_type = "advance_amount_receipt";
        // if($this->checkEligibilityForDocumentVerification($data['consumer_applications'])){
            $docStatus = $this->checkDocumentStatus($data['consumer_applications']->id, $document_type);
            if ($docStatus == "0"){
                $checklistData31['disbursement checklist done']['section']['section_name'][$info['key']]['applicant']['content']['value'] = "";
            } else if ($docStatus == "1" && $docVerificationPermission) {
                $checklistData31['disbursement checklist done']['section']['section_name'][$info['key']]['applicant']['content']['verify_document'] = true;
            }
        // }
        unset($info);

        $info['group_name'] = 'disbursement checklist done';
        $info['customer_type'] = 'applicant';
        // $info['group_display'] = 0;
        // $info['application_data_display'] = 0;
        $info['name'] = 'TFR Report';
        $info['key'] = 'tfr';
        $info['value'] = $file_path['tfr'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'pdf';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = '';
        $info['field_accept_value'] = 'application/pdf, image/*';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData49 = $this->checklistStructure($info);
        $document_type = "tfr";
        // if($this->checkEligibilityForDocumentVerification($data['consumer_applications'])){
            $docStatus = $this->checkDocumentStatus($data['consumer_applications']->id, $document_type);
            if ($docStatus == "0"){
                $checklistData49['disbursement checklist done']['section']['section_name'][$info['key']]['applicant']['content']['value'] = "";
            } else if ($docStatus == "1" && $docVerificationPermission) {
                $checklistData49['disbursement checklist done']['section']['section_name'][$info['key']]['applicant']['content']['verify_document'] = true;
            }
        // }
        unset($info);
        
        $info['group_name'] = 'disbursement checklist done';
        $info['customer_type'] = 'applicant';
        $info['name'] = 'Final quotation / bill';
        $info['key'] = 'proforma';
        $info['value'] = $file_path['proforma'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'pdf';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = '';
        $info['field_accept_value'] = 'application/pdf, image/*';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData555 = $this->checklistStructure($info);
        $document_type = "proforma";
        // if($this->checkEligibilityForDocumentVerification($data['consumer_applications'])){
            $docStatus = $this->checkDocumentStatus($data['consumer_applications']->id, $document_type);
            if ($docStatus == "0"){
                $checklistData555['disbursement checklist done']['section']['section_name'][$info['key']]['applicant']['content']['value'] = "";
            } else if ($docStatus == "1" && $docVerificationPermission) {
                $checklistData555['disbursement checklist done']['section']['section_name'][$info['key']]['applicant']['content']['verify_document'] = true;
            }
        // }
        unset($info);
        $info['group_name'] = 'disbursement checklist done';
        $info['customer_type'] = 'applicant';
        $info['name'] = 'Solar quotation';
        $info['key'] = 'solar_quotation';
        $info['value'] = $file_path['solar_quotation'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'pdf';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = '';
        $info['field_accept_value'] = 'application/pdf, image/*';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData50 = $this->checklistStructure($info);
        $document_type = "solar_quotation";
        $docStatus = $this->checkDocumentStatus($data['consumer_applications']->id, $document_type);
        if ($docStatus == "0"){
            $checklistData50['disbursement checklist done']['section']['section_name'][$info['key']]['applicant']['content']['value'] = "";
        } else if ($docStatus == "1" && $docVerificationPermission) {
            $checklistData50['disbursement checklist done']['section']['section_name'][$info['key']]['applicant']['content']['verify_document'] = true;
        }
        unset($info);
        
        $info['group_name'] = 'disbursement checklist done';
        $info['customer_type'] = 'applicant';
        // $info['group_display'] = 0;
        // $info['application_data_display'] = 0;
        $info['name'] = 'disbursement advice';
        $info['key'] = 'pro_forma_invoice';
        $info['value'] = $file_path['da'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'pdf';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = '';
        $info['field_accept_value'] = 'application/pdf, image/*';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData32 = $this->checklistStructure($info);
        unset($info);
        // $info['group_name'] = 'disbursement checklist done';
        // $info['customer_type'] = 'applicant';
        // // $info['group_display'] = 0;
        // // $info['application_data_display'] = 0;
        // $info['name'] = 'video (atta chakki)';
        // $info['key'] = 'atta_chakki_video';
        // $info['value'] = $file_path['atta_chakki_video'] ?? '';
        // $info['field_type'] = 'link';
        // $info['field_content'] = 'video';
        // $info['field_required'] = 0;
        // $info['field_display'] = 1;
        // $info['field_value'] = '';
        // $info['content_display'] = 1;
        // $info['checklist_page'] = 'disbursement';
        // $checklistData33 = $this->checklistStructure($info);
        // unset($info);
        $info['group_name'] = 'disbursement checklist done';
        $info['customer_type'] = 'applicant';
        // $info['group_display'] = 0;
        // $info['application_data_display'] = 0;
        $info['name'] = 'Credit PD Video ( Drive link)';
        $info['key'] = 'credit_approval_video';
        $info['value'] = $data['consumer_applications']->application_element->credit_approval_video ?? '';
        $info['field_type'] = 'input';
        $info['field_content'] = 'text';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_placeholder'] = 'paste link here';
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData46 = $this->checklistStructure($info);
        unset($info);
        $info['group_name'] = 'disbursement checklist done';
        $info['customer_type'] = 'applicant';
        // $info['group_display'] = 0;
        // $info['application_data_display'] = 0;
        $info['name'] = 'credit appraisal memo';
        $info['key'] = 'credit_appraisal_memo';
        $info['value'] = $file_path['credit_appraisal_memo'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'pdf';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = '';
        $info['field_accept_value'] = 'application/pdf, image/*';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData40 = $this->checklistStructure($info);
        unset($info);
        $info['group_name'] = 'disbursement checklist done';
        $info['customer_type'] = 'applicant';
        // $info['group_display'] = 0;
        // $info['application_data_display'] = 0;
        $info['name'] = 'cpv report';
        $info['key'] = 'cpv_report';
        $info['value'] = $file_path['cpv_report'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'pdf';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = '';
        $info['field_accept_value'] = 'application/pdf, image/*';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData41 = $this->checklistStructure($info);
        unset($info);

        $callsLog = CallLogs::where('_id', $id)->where('id_type', 'application_id');
        $data['callLogs'] = $callsLog->whereNotNull('recording')->where('recording', '!=', '')->get(['id', 'to', 'from', 'direction', 'created_at', 'recording', 'purpose']);

        $data['verification_call_recording'] = $callsLog->where('purpose', 'verification_call')
            ->where(function ($query){
            $query->whereIn('status',['in-progress','completed']);
            })->orderBy('status','asc')->first(['id', 'to', 'from', 'direction', 'created_at', 'recording', 'purpose','status']);
        $callsLogs = $callsLog->whereNotNull('recording')->where('recording', '!=', '')->where('purpose', 'verification_call')->first(['id', 'recording', 'purpose']);
        $file_path['call_recording'] = $file_path['call_recording'] ?? '';
        if (!isset($callsLogs->id)) {
            $callsLogs = new \stdClass();
            $callsLogs->recording = '/admin/consumer-application/get-documents/'.$file_path['call_recording'];
            $callsLogs->id = 1;
            $callsLogs->purpose = 'Call Manually added';
        }
        $callStatus = isset($callsLogs->id) && !empty($file_path['call_recording']) ? "<i class='fa fa-file-audio-o'></i> <a style='font-size: 12px;color:#7b7e8a;' href='" . $callsLogs->recording . "'>" . ucwords(str_replace('_', ' ', $callsLogs->purpose)) . "</a>" : '';

        $info['group_name'] = 'disbursement checklist done';
        $info['customer_type'] = 'applicant';
        // $info['group_display'] = 0;
        // $info['application_data_display'] = 0;
        $info['name'] = 'call recording';
        $info['key'] = 'call_recording_modal_1';
        if(count($data['callLogs']) > 0){
            $info['value'] = 'call_recording';
            $info['field_type'] = 'input';
            $info['field_content'] = 'button';
            $info['field_required'] = 0;
            $info['field_display'] = 0;
        }elseif($callStatus != ''){
            $info['value'] = $callStatus;
            $info['field_type'] = 'custom';
            $info['field_content'] = 'link';
            $info['field_required'] = ($isDigioCompleted) ? 0 : 1;
            $info['field_display'] = 1;
            $info['field_accept_value'] = '.mp3,audio/*';
        }else{
            $info['value'] = $callStatus;
            $info['field_type'] = 'link';
            $info['field_content'] = 'audio';
            
            if($isDigioCompleted){
                $info['field_required'] = 0;
            } else {
                $info['field_required'] = 1;
            }

            $info['field_display'] = 1;
            $info['field_accept_value'] = '.mp3,audio/*';
        }
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData47 = $this->checklistStructure($info);
        unset($info);

        if ($data['consumer_applications']->emi && $data['consumer_applications']->emi->processing_fee > 0) {
            $processing_fee_status = '<span style="font-size:12px;">Processing fee will be received from merchant</span>';
            if (isset($data['consumer_applications']->merchant->is_collected)) {
                if (($data['consumer_applications']->proFormaInvoice && is_null($data['consumer_applications']->proFormaInvoice->processing_fee_by_merchant) && $data['consumer_applications']->merchant->is_collected == 0) || (isset($data['consumer_applications']->proFormaInvoice->processing_fee_by_merchant) && $data['consumer_applications']->proFormaInvoice->processing_fee_by_merchant == 0)) {
                    if (isset($file_path['processing_fee_receipt'])) {
                        $processing_fee_status = '<span style="font-size:12px;"><a class="btn btn-primary col-md-12" href="/admin/consumer-application/get-documents/'.$file_path['processing_fee_receipt'].'" target="_blank">View Details</a></span>'; //Processing fee received from customer
                    } else if ((isset($_GET['state']) && $_GET['state'] == 'disbursement checklist done') || (!isset($_GET['state']) && $data['consumer_applications']->state != 'waiting for documents')) {
                        $accountingController = new AccountingController();
                        $processingDue = $accountingController->getApplicationDueAmount($data['consumer_applications']->id);
                        if ($processingDue['processing_fee_due'] > 0) {
                            $t = "'Processing fee not received from customer'";
                            $isRequired = '';
                            $offer = MerchantOffers::where('id', $data['consumer_applications']->emi->offer_id)->first(['processing_fee_first_emi']);
                            if (in_array('disbursement checklist done', $pastLogs)) {
                                $isRequired = 'required="required"';
                            }

                            $isRequiredProcessingFee = 'required="required"';

                            if(isset($offer->processing_fee_first_emi) && $offer->processing_fee_first_emi) {
                                $processing_fee_status = '<span style="font-size:12px;">Processing Fees will be collected with 1st EMI</span>';
                            }else{
                                $processing_fee_status = '<i class="fa fa-exclamation-triangle" aria-hidden="true" style="margin-right: 6px;color: red;" title="Processing fee not received from customer"></i><input type="text" style="width: 0;height: 0;position: absolute;border: 0;outline: none;" oninvalid="this.setCustomValidity(' . $t . ')" name="pros" ' . $isRequired . ' '.$isRequiredProcessingFee.'/><span style="font-size:12px;color:red">Processing fee of Rs. ' . $processingDue['processing_fee_due'] . ' is pending from customer</span>';
                            }
                        } else {
                            $processing_fee_status = '<span style="font-size:12px;"><a href="javascript:void(0);" class="btn btn-primary col-md-12" data-toggle="modal" data-target="#viewProcessingFee">View Details</a></span>'; //Processing fee received from customer
                        }
                    }
                }
            }
        } else {
            $processing_fee_status = '<span style="font-size:12px;">Processing fee is 0</span>';

        }
        $data['processingFeeData'] = $this->getProcessingFeeData($id);

        $info['group_name'] = 'disbursement checklist done';
        $info['customer_type'] = 'applicant';
        // $info['group_display'] = 0;
        // $info['application_data_display'] = 0;
        $info['name'] = 'processing fee status';
        $info['key'] = 'processing_fee';
        $info['value'] = $processing_fee_status ?? '';
        $info['field_type'] = 'custom';
        $info['field_content'] = 'file';
        $info['field_required'] = 1;
        $info['field_display'] = 1;
        $info['field_accept_value'] = 'application/pdf, image/*';
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData48 = $this->checklistStructure($info);
        unset($info);
        $checklistData301 = [];
        if($file_path['fd_receipt'] ?? ''){
        $info['group_name'] = 'disbursement checklist done';
        $info['customer_type'] = 'applicant';
        $info['name'] = 'FD Receipt';
        $info['key'] = 'FD Receipt';
        $info['value'] = $file_path['fd_receipt'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'pdf';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData301 = $this->checklistStructure($info);
        unset($info);
        }
        $checklistData302 = [];
        if($file_path['fd_lien_letter'] ?? ''){
        $info['group_name'] = 'disbursement checklist done';
        $info['customer_type'] = 'applicant';
        $info['name'] = 'FD lien letter';
        $info['key'] = 'FD lien letter';
        $info['value'] = $file_path['fd_lien_letter'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'pdf';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData302 = $this->checklistStructure($info);
        unset($info);
        }
        
        $checklistData305 = [];
        if($file_path['commissioning_certificate'] ?? ''){
        $info['group_name'] = 'disbursement checklist done';
        $info['customer_type'] = 'applicant';
        $info['name'] = 'Commissioning certificate';
        $info['key'] = 'commissioning_certificate';
        $info['value'] = $file_path['commissioning_certificate'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'pdf';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData305 = $this->checklistStructure($info);
        unset($info);
        }
        $checklistData306 = [];
        if($file_path['Sync Report'] ?? ''){
        $info['group_name'] = 'disbursement checklist done';
        $info['customer_type'] = 'applicant';
        $info['name'] = 'Sync Report';
        $info['key'] = 'Sync Report';
        $info['value'] = $file_path['Sync Report'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'pdf';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData306 = $this->checklistStructure($info);
        unset($info);
        }
        $checklistData307 = [];
        if($file_path['net_metering_agreement'] ?? ''){
        $info['group_name'] = 'disbursement checklist done';
        $info['customer_type'] = 'applicant';
        $info['name'] = 'Net Metering Agreement';
        $info['key'] = 'net_metering_agreement';
        $info['value'] = $file_path['net_metering_agreement'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'pdf';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData307 = $this->checklistStructure($info);
        unset($info);
        }
        $checklistData308 = [];
        if($file_path['RM visit Checklist'] ?? ''){
        $info['group_name'] = 'disbursement checklist done';
        $info['customer_type'] = 'applicant';
        $info['name'] = 'RM visit Checklist';
        $info['key'] = 'RM visit Checklist';
        $info['value'] = $file_path['RM visit Checklist'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'pdf';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData308 = $this->checklistStructure($info);
        unset($info);
        }
        $checklistData309 = [];
        if($file_path['RM visit photo'] ?? ''){
        $info['group_name'] = 'disbursement checklist done';
        $info['customer_type'] = 'applicant';
        $info['name'] = 'RM visit photo';
        $info['key'] = 'RM visit photo';
        $info['value'] = $file_path['RM visit photo'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'pdf';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData309 = $this->checklistStructure($info);
        unset($info);
        }
        $checklistData310 = [];
        if($file_path['installation_photo'] ?? ''){
        $info['group_name'] = 'disbursement checklist done';
        $info['customer_type'] = 'applicant';
        $info['name'] = 'Installation Photo';
        $info['key'] = 'installation_photo';
        $info['value'] = $file_path['installation_photo'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'pdf';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData310 = $this->checklistStructure($info);
        unset($info);
        }
        $checklistData311 = [];
        if($file_path['electricity_bill'] ?? ''){
        $info['group_name'] = 'disbursement checklist done';
        $info['customer_type'] = 'applicant';
        $info['name'] = 'Electricity bill';
        $info['key'] = 'electricity_bill';
        $info['value'] = $file_path['electricity_bill'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'pdf';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData311 = $this->checklistStructure($info);
        unset($info);
        }
        $checklistData312 = [];
        if($file_path['e_bill_validation'] ?? ''){
        $info['group_name'] = 'disbursement checklist done';
        $info['customer_type'] = 'applicant';
        $info['name'] = 'E-bill validation';
        $info['key'] = 'e_bill_validation';
        $info['value'] = $file_path['e_bill_validation'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'pdf';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData312 = $this->checklistStructure($info);
        unset($info);
        }
        $checklistData313 = [];
        if($file_path['work_completion_report'] ?? ''){
        $info['group_name'] = 'disbursement checklist done';
        $info['customer_type'] = 'applicant';
        $info['name'] = 'Work completion report';
        $info['key'] = 'work_completion_report';
        $info['value'] = $file_path['work_completion_report'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'pdf';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData313 = $this->checklistStructure($info);
        unset($info);
        }
        $checklistData314 = [];
        if($file_path['e_bill_with_solar_reading'] ?? ''){
        $info['group_name'] = 'disbursement checklist done';
        $info['customer_type'] = 'applicant';
        $info['name'] = 'E-bill with solar reading';
        $info['key'] = 'e_bill_with_solar_reading';
        $info['value'] = $file_path['e_bill_with_solar_reading'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'pdf';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData314 = $this->checklistStructure($info);
        unset($info);
        }
        $checklistData315 = [];
        if($file_path['chakki_running_on_panel_video'] ?? ''){
        $info['group_name'] = 'disbursement checklist done';
        $info['customer_type'] = 'applicant';
        $info['name'] = 'Chakki Running on panel video';
        $info['key'] = 'chakki_running_on_panel_video';
        $info['value'] = $file_path['chakki_running_on_panel_video'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'pdf';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData315 = $this->checklistStructure($info);
        unset($info);
        }
        $checklistData316 = [];
        if($file_path['noc_for_solar_installation'] ?? ''){
        $info['group_name'] = 'disbursement checklist done';
        $info['customer_type'] = 'applicant';
        $info['name'] = 'NOC for Solar Installation';
        $info['key'] = 'noc_for_solar_installation';
        $info['value'] = $file_path['noc_for_solar_installation'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'pdf';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData316 = $this->checklistStructure($info);
        unset($info);
        }
        $checklistData317 = [];
        if($file_path['tax_invoice'] ?? ''){
        $info['group_name'] = 'disbursement checklist done';
        $info['customer_type'] = 'applicant';
        $info['name'] = 'Tax Invoice';
        $info['key'] = 'tax_invoice';
        $info['value'] = $file_path['tax_invoice'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'pdf';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData317 = $this->checklistStructure($info);
        unset($info);
        }
        $checklistData334 = [];
        if($file_path['pg_agreement_1'] ?? ''){
        $info['group_name'] = 'disbursement checklist done';
        $info['customer_type'] = 'applicant';
        $info['name'] = 'PG agreement 1';
        $info['key'] = 'pg_agreement_1';
        $info['value'] = $file_path['pg_agreement_1'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'pdf';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData334 = $this->checklistStructure($info);
        unset($info);
        }
        $checklistData319 = [];
        if($file_path['pg_agreement_2'] ?? ''){
        $info['group_name'] = 'disbursement checklist done';
        $info['customer_type'] = 'applicant';
        $info['name'] = 'PG agreement 2';
        $info['key'] = 'pg_agreement_2';
        $info['value'] = $file_path['pg_agreement_2'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'pdf';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData319 = $this->checklistStructure($info);
        unset($info);
        }
        $checklistData320 = [];
        if($file_path['pg_agreement_3'] ?? ''){
        $info['group_name'] = 'disbursement checklist done';
        $info['customer_type'] = 'applicant';
        $info['name'] = 'PG agreement 3';
        $info['key'] = 'pg_agreement_3';
        $info['value'] = $file_path['pg_agreement_3'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'pdf';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData320 = $this->checklistStructure($info);
        unset($info);
        }
        $checklistData321 = [];
        if($file_path['pg_signed_kyc_document'] ?? ''){
        $info['group_name'] = 'disbursement checklist done';
        $info['customer_type'] = 'applicant';
        $info['name'] = 'PG signed KYC document';
        $info['key'] = 'PG signed KYC document';
        $info['value'] = $file_path['pg_signed_kyc_document'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'pdf';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData321 = $this->checklistStructure($info);
        unset($info);
        }
        $checklistData322 = [];
        if($file_path['affidavit_1'] ?? ''){
        $info['group_name'] = 'disbursement checklist done';
        $info['customer_type'] = 'applicant';
        $info['name'] = 'Affidavit 1';
        $info['key'] = 'Affidavit 1';
        $info['value'] = $file_path['affidavit_1'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'pdf';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData322 = $this->checklistStructure($info);
        unset($info);
        }
        $checklistData323 = [];
        if($file_path['affidavit_2'] ?? ''){
        $info['group_name'] = 'disbursement checklist done';
        $info['customer_type'] = 'applicant';
        $info['name'] = 'Affidavit 2';
        $info['key'] = 'Affidavit 2';
        $info['value'] = $file_path['affidavit_2'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'pdf';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData323 = $this->checklistStructure($info);
        unset($info);
        }
        $checklistData324 = [];
        if($file_path['registration_certificate'] ?? ''){
        $info['group_name'] = 'disbursement checklist done';
        $info['customer_type'] = 'applicant';
        $info['name'] = 'Registration Certificate';
        $info['key'] = 'Registration Certificate';
        $info['value'] = $file_path['registration_certificate'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'pdf';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData324 = $this->checklistStructure($info);
        unset($info);
        }
        $checklistData325 = [];
        if($file_path['board_resolution'] ?? ''){
        $info['group_name'] = 'disbursement checklist done';
        $info['customer_type'] = 'applicant';
        $info['name'] = 'Board resolution';
        $info['key'] = 'Board resolution';
        $info['value'] = $file_path['board_resolution'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'pdf';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData325 = $this->checklistStructure($info);
        unset($info);
        }
        $checklistData326 = [];
        if($file_path['incorporation_certificate'] ?? ''){
        $info['group_name'] = 'disbursement checklist done';
        $info['customer_type'] = 'applicant';
        $info['name'] = 'Incorporation Certificate';
        $info['key'] = 'Incorporation Certificate';
        $info['value'] = $file_path['incorporation_certificate'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'pdf';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData326 = $this->checklistStructure($info);
        unset($info);
        }
        $checklistData327 = [];
        if($file_path['moa'] ?? ''){
        $info['group_name'] = 'disbursement checklist done';
        $info['customer_type'] = 'applicant';
        $info['name'] = 'MOA';
        $info['key'] = 'MOA';
        $info['value'] = $file_path['moa'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'pdf';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData327 = $this->checklistStructure($info);
        unset($info);
        }
        $checklistData328 = [];
        if($file_path['aoa'] ?? ''){
        $info['group_name'] = 'disbursement checklist done';
        $info['customer_type'] = 'applicant';
        $info['name'] = 'AOA';
        $info['key'] = 'AOA';
        $info['value'] = $file_path['aoa'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'pdf';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData328 = $this->checklistStructure($info);
        unset($info);
        }
        $checklistData329 = [];
        if($file_path['list_of_member'] ?? ''){
        $info['group_name'] = 'disbursement checklist done';
        $info['customer_type'] = 'applicant';
        $info['name'] = 'List of Member';
        $info['key'] = 'List of Member';
        $info['value'] = $file_path['list_of_member'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'pdf';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData329 = $this->checklistStructure($info);
        unset($info);
        }
        $checklistData330 = [];
        if($file_path['bye_law'] ?? ''){
        $info['group_name'] = 'disbursement checklist done';
        $info['customer_type'] = 'applicant';
        $info['name'] = 'Bye Law';
        $info['key'] = 'Bye Law';
        $info['value'] = $file_path['bye_law'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'pdf';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData330 = $this->checklistStructure($info);
        unset($info);
        }
        $checklistData331 = [];
        if($file_path['oc'] ?? ''){
        $info['group_name'] = 'disbursement checklist done';
        $info['customer_type'] = 'applicant';
        $info['name'] = 'OC';
        $info['key'] = 'OC';
        $info['value'] = $file_path['oc'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'pdf';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData331 = $this->checklistStructure($info);
        unset($info);
        }
        $checklistData332 = [];
        if($file_path['cc'] ?? ''){
        $info['group_name'] = 'disbursement checklist done';
        $info['customer_type'] = 'applicant';
        $info['name'] = 'CC';
        $info['key'] = 'CC';
        $info['value'] = $file_path['cc'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'pdf';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData332 = $this->checklistStructure($info);
        unset($info);
        }
        $checklistData333 = [];
        if($file_path['trust_deed'] ?? ''){
        $info['group_name'] = 'disbursement checklist done';
        $info['customer_type'] = 'applicant';
        $info['name'] = 'Trust Deed';
        $info['key'] = 'Trust Deed';
        $info['value'] = $file_path['trust_deed'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'pdf';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData333 = $this->checklistStructure($info);
        unset($info);
        }
        $checklistData336 = [];
        if($file_path['partnership_deed'] ?? ''){
            $info['group_name'] = 'disbursement checklist done';
            $info['customer_type'] = 'applicant';
            $info['name'] = 'Partnership Deed';
            $info['key'] = 'partnership_deed';
            $info['value'] = $file_path['partnership_deed'] ?? '';
            $info['field_type'] = 'link';
            $info['field_content'] = 'pdf';
            $info['field_required'] = 0;
            $info['field_display'] = 1;
            $info['field_value'] = '';
            $info['content_display'] = 1;
            $info['checklist_page'] = 'disbursement';
            $checklistData336 = $this->checklistStructure($info);
            unset($info);
        }
        $checklistData335 = [];
        if(($file_path['Net Metering proof'] ?? '') || ($file_path['commissioning_certificate'] ?? '') || ($file_path['DCR Report'] ?? '') || ($file_path['E-bill with solar generation'] ?? '') || ($file_path['release_order'] ?? '') || ($file_path['sync_report'] ?? '')){
            $info['group_name'] = 'disbursement checklist done';
            $info['customer_type'] = 'applicant';
            $info['name'] = 'Net Metering proof';
            $info['key'] = 'Net Metering proof';
            $info['value'] =
    $file_path['Net Metering proof'] ??
    $file_path['commissioning_certificate'] ??
    $file_path['DCR Report'] ??
    $file_path['E-bill with solar generation'] ??
    $file_path['release_order'] ??
    $file_path['sync_report'] ??
    '';
            $info['field_type'] = 'link';
            $info['field_content'] = 'pdf';
            $info['field_required'] = 0;
            $info['field_display'] = 1;
            $info['field_value'] = '';
            $info['content_display'] = 1;
            $info['checklist_page'] = 'disbursement';
            $checklistData335 = $this->checklistStructure($info);
            unset($info);
        }

        $info['group_name'] = 'references';
        $info['customer_type'] = 'applicant';
        // $info['group_display'] = 0;
        // $info['application_data_display'] = 0;
        $info['name'] = 'reference 1';
        $info['key'] = 'reference_1';
        $info['value'] = $file_path['reference_1'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'pdf';
        $info['field_required'] = 0;
        $info['field_display'] = 0;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData42 = $this->checklistStructure($info);
        unset($info);

        $info['group_name'] = 'references';
        $info['customer_type'] = 'applicant';
        // $info['group_display'] = 0;
        // $info['application_data_display'] = 0;
        $info['name'] = 'system reference 1';
        $info['key'] = 'system_reference_1';
        $info['value'] = isset($data['consumer_applications']->application_element->reference_name_1) ? '<input field="text" value="'.$data['consumer_applications']->application_element->reference_name_1.'" placeholder="reference name"><br><input field="text" value="'.$data['consumer_applications']->application_element->reference_contact_1.'" placeholder="reference contact"><br><input field="text" value="'.$data['consumer_applications']->application_element->reference_relation_1.'" placeholder="reference relation">' : '';
        $info['field_type'] = 'custom';
        $info['field_content'] = 'text';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData43 = $this->checklistStructure($info);
        unset($info);
        //$info['group_name'] = 'references';
        //$info['customer_type'] = 'applicant';
        // $info['group_display'] = 0;
        // $info['application_data_display'] = 0;
        //$info['name'] = 'reference 2';
        //$info['key'] = 'reference_2';
        //$info['value'] = $file_path['reference_2'] ?? '';
        //$info['field_type'] = 'link';
        //$info['field_content'] = 'pdf';
        //$info['field_required'] = 0;
        //$info['field_display'] = 0;
        //$info['field_value'] = '';
        //$info['content_display'] = 1;
        //$info['checklist_page'] = 'disbursement';
        //$checklistData44 = $this->checklistStructure($info);
        //unset($info);
        $info['group_name'] = 'references';
        $info['customer_type'] = 'applicant';
        // $info['group_display'] = 0;
        // $info['application_data_display'] = 0;
        $info['name'] = 'system reference 2';
        $info['key'] = 'system_reference_2';
        $info['value'] = isset($data['consumer_applications']->application_element->reference_name_2) ? '<input field="text" value="'.$data['consumer_applications']->application_element->reference_name_2.'" placeholder="reference name"><br><input field="text" value="'.$data['consumer_applications']->application_element->reference_contact_2.'" placeholder="reference contact"><br><input field="text" value="'.$data['consumer_applications']->application_element->reference_relation_2.'" placeholder="reference relation">' : '';
        $info['field_type'] = 'custom';
        $info['field_content'] = 'text';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData45 = $this->checklistStructure($info);
        unset($info);


        $info['group_name'] = 'Product Verification';
        $info['customer_type'] = 'applicant';
        // $info['group_display'] = 0;
        // $info['application_data_display'] = 0;
        $info['name'] = 'merchant email confirmation / signed DA';
        $info['key'] = 'merchant_confirmation';
        $info['value'] = $file_path['merchant_confirmation'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'pdf';
        $info['field_required'] = 0;
        $info['field_display'] = 0;
        $info['field_value'] = '';
        $info['field_accept_value'] = 'application/pdf, image/*';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData34 = $this->checklistStructure($info);
        unset($info);

        $info['group_name'] = 'Product Verification';
        $info['customer_type'] = 'applicant';
        // $info['group_display'] = 0;
        // $info['application_data_display'] = 0;
        $info['name'] = 'final quotation / final bill';
        $info['key'] = 'quotation_bill';
        $info['value'] = $file_path['quotation_bill'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'pdf';
        $info['field_required'] = 0;
        $info['field_display'] = 0;
        $info['field_value'] = '';
        $info['field_accept_value'] = 'application/pdf, image/*';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData234 = $this->checklistStructure($info);
        unset($info);

        if($this->isDisbPostInstallationCase($id)){
            $info['group_name'] = 'Product Verification';
            $info['customer_type'] = 'applicant';
            // $info['group_display'] = 0;
            // $info['application_data_display'] = 0;
            $info['name'] = 'Solar Installation Proof';
            $info['key'] = 'solar_installation_proof';
            $info['value'] = $file_path['solar_installation_proof'] ?? '';
            $info['field_type'] = 'link';
            // $info['field_content'] = 'pdf';
            $info['field_required'] = 0;
            $info['field_display'] = 0;
            $info['field_value'] = '';
            $info['field_accept_value'] = 'application/pdf, image/*';
            $info['content_display'] = 1;
            $info['checklist_page'] = 'disbursement';
            $checklistData235 = $this->checklistStructure($info);
            unset($info);
        }else{
            $checklistData235 = [];
        }
        $risk_categories = self::$risk_category;

        $risk_category_options = '';

        if($data['consumer_applications']->application_element->risk_category !== "W"){
                            unset($risk_categories["W"]);
                        }

        // Iterate through risk categories to construct options
        foreach ($risk_categories as $key => $label) {
            if (in_array($key, ['A','B','C','D','E','F','G','H'])) {
                $risk_category_priority = 'A High Risk- ';
            }
            elseif (in_array($key, ['I','J','K','L','M'])) {
                $risk_category_priority = 'B Medium Risk- ';
            }
            else {
                if($key == "W"){
                    $risk_category_priority = 'C Low Risk';
                }else{
                    $risk_category_priority = 'C Low Risk- ';
                }

            }
            $selected = (isset($data['consumer_applications']->application_element->risk_category) &&
                        $data['consumer_applications']->application_element->risk_category === $key)
                        ? 'selected="selected"'
                        : '';

            // Append the option to the risk category data
            $risk_category_options.= '<option ' . $selected . ' value="' . htmlspecialchars($key) . '">' .htmlspecialchars($risk_category_priority). htmlspecialchars($label) . '</option>';


        }
        $risk_category_value = '<div><select class="form-control is_include_verification" name="selected_risk_category"  style="top: 10px;left: 84px;max-width: 433px;"><option value="">Select KYC Risk category</option>'. $risk_category_options .'</select></div>';


        $info['group_name'] = 'personal Details';
        $info['customer_type'] = 'applicant';
        // $info['group_display'] = 0;
        $info['application_data_display'] = 0;
        $info['name'] = 'age(20 to 65 years)';
        $info['key'] = 'age';
        $info['value'] = \Carbon\Carbon::parse($data['consumer_applications']->dob)->age;
        $info['field_type'] = 'input';
        $info['field_content'] = 'number';
        $info['field_required'] = 1;
        $info['field_display'] = 1;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData107 = $this->checklistStructure($info);
        unset($info);
        $info['group_name'] = 'personal Details';
        $info['customer_type'] = 'co-applicant';
        // $info['group_display'] = 0;
        $info['application_data_display'] = 0;
        $info['name'] = 'age(20 to 65 years)';
        $info['key'] = 'age';
        $info['value'] =isset($data['consumer_applications']->co_applicant_name) ? \Carbon\Carbon::parse($data['consumer_applications']->co_applicant_dob)->age : '';
        $info['field_type'] = 'input';
        $info['field_content'] = 'number';
        $info['field_required'] = 0;
        $info['field_display'] = 0;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData69 = $this->checklistStructure($info);
        unset($info);
        $info['group_name'] = 'personal Details';
        $info['customer_type'] = 'applicant';
        // $info['group_display'] = 0;
        $info['application_data_display'] = 0;
        $info['name'] = 'KYC Risk Category';
        $info['key'] = 'risk category';
        $info['value'] = $risk_category_value;
        $info['field_type'] = 'custom';
        $info['field_content'] = 'dropdown';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData = $this->checklistStructure($info);
        unset($info);
        // $info['group_name'] = 'personal Details';
        // $info['customer_type'] = 'co-applicant';
        // // $info['group_display'] = 0;
        // $info['application_data_display'] = 0;
        // $info['name'] = 'KYC Risk Category';
        // $info['key'] = 'risk category';
        // $info['value'] = $risk_category_value;
        // $info['field_type'] = 'custom';
        // $info['field_content'] = 'dropdown';
        // $info['field_required'] = 0;
        // $info['field_display'] = 0;
        // $info['field_value'] = '';
        // $info['content_display'] = 1;
        // $info['checklist_page'] = 'disbursement';
        // $checklistData = $this->checklistStructure($info);
        // unset($info);

        $info['group_name'] = 'personal Details';
        $info['customer_type'] = 'applicant';
        // $info['group_display'] = 0;
        $info['name'] = 'contact';
        $info['key'] = 'mobile_number';
        $info['value'] = $data['consumer_applications']->mobile_number;
        $info['field_type'] = 'input';
        $info['field_content'] = 'number';
        $info['field_required'] = 1;
        $info['field_display'] = 1;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        // $info['section_name'] = 'logge';
        $info['checklist_page'] = 'disbursement';
        $checklistData4 = $this->checklistStructure($info);
        unset($info);
        $info['group_name'] = 'personal Details';
        $info['customer_type'] = 'co-applicant';
        // $info['group_display'] = 0;
        $info['name'] = 'contact';
        $info['key'] = 'mobile_number';
        $info['value'] = $data['consumer_applications']->co_applicant_mobile_number ?? '';
        $info['field_type'] = 'input';
        $info['field_content'] = 'number';
        $info['field_required'] = 0;
        $info['field_display'] = 0;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData8 = $this->checklistStructure($info);
        unset($info);

        $tele_verf_status = (isset($data['consumer_applications']->user->is_otp_verified) && ($data['consumer_applications']->user->is_otp_verified == 1)) ? '1' : ((isset($data['consumer_applications']->Checklist->tele_verification) && $data['consumer_applications']->Checklist->tele_verification == 1) ? '1' : '0');

        $info['group_name'] = 'personal Details';
        $info['customer_type'] = 'applicant';
        // $info['group_display'] = 0;
        $info['name'] = 'tele verification';
        $info['key'] = 'tele_verification';
        $info['value'] = $tele_verf_status;
        $info['field_type'] = 'input';
        $info['field_content'] = 'radio';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = [1,0];
        $info['content_display'] = 1;
        // $info['section_name'] = 'logged';
        $info['checklist_page'] = 'disbursement';
        $checklistData5 = $this->checklistStructure($info);
        unset($info);

        $co_mobile = $data['consumer_applications']->co_applicant_mobile_number ?? null;
        $is_verified_co_mobile = User::where('mobile_number',$co_mobile)->first(['id','is_otp_verified']);
        $co_mobile_verify_status = isset($is_verified_co_mobile->is_otp_verified) ? '1' : '0';
        $info['group_name'] = 'personal Details';
        $info['customer_type'] = 'co-applicant';
        // $info['group_display'] = 0;
        // $info['application_data_display'] = 0;
        $info['name'] = 'tele verification';
        $info['key'] = 'tele_verification';
        $info['value'] = $co_mobile_verify_status;
        $info['field_type'] = 'input';
        $info['field_content'] = 'radio';
        $info['field_required'] = 0;
        $info['field_display'] = 0;
        $info['field_value'] = [1,0];
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData1 = $this->checklistStructure($info);
        unset($info);

        if(isset($data['consumer_applications']->Checklist->negative_profession)){
            $acceptableDataReason = $this->AcceptableDataReason('negative_profession', $data['consumer_applications'], true);
            $acceptableDataReason['Reason'] = $acceptableDataReason['Reason']!='' ? '1' : '0';
            $negativeProfession = NegativeProfile::where('id',$data['consumer_applications']->Checklist->negative_profession)->first(['name']);
        }
        $negative_prof = (isset($data['consumer_applications']->Checklist->negative_profession) && !empty($data['consumer_applications']->Checklist->negative_profession)) ? [isset($negativeProfession->name) ? $negativeProfession->name : $acceptableDataReason['Reason']] : '0';
        $info['group_name'] = 'personal Details';
        $info['customer_type'] = 'applicant';
        // $info['group_display'] = 0;
        $info['application_data_display'] = 0;
        $info['name'] = 'check negative profession';
        $info['key'] = 'negative_profession';
        $info['value'] = $negative_prof;
        $info['field_type'] = 'input';
        $info['field_content'] = 'radio';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = [1,0];
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData6 = $this->checklistStructure($info);
        unset($info);


        $info['group_name'] = 'personal Details';
        $info['customer_type'] = 'co-applicant';
        // $info['group_display'] = 0;
        // $info['application_data_display'] = 0;
        $info['name'] = 'check negative profession';
        $info['key'] = 'negative_profession';
        $info['value'] = '0';
        $info['field_type'] = 'input';
        $info['field_content'] = 'radio';
        $info['field_required'] = 0;
        $info['field_display'] = 0;
        $info['field_value'] = [1,0];
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData7 = $this->checklistStructure($info);
        unset($info);

        $creditInfo = ($data['consumer_applications']->creditReport)->toArray();
        $pan_info = '';
        $co_pan_info = '';
        foreach($creditInfo as $k => $t){
            if($t['applicant_type'] == 1){
                $pan_info = $t['panValidation'];
            }elseif($t['applicant_type'] == 2){
                $co_pan_info = $t['panValidation'];
            }
        }

        $info['group_name'] = 'personal Details';
        $info['customer_type'] = 'applicant';
        // $info['group_display'] = 0;
        $info['name'] = 'pan validation';
        $info['key'] = 'pan_validation';
        if($pan_info != ''){
            $info['value'] = $pan_info;
            $info['field_type'] = 'input';
            $info['field_content'] = 'button';
        }else{
            $info['value'] = $file_path['pan_validation'] ?? '';
            $info['field_type'] = 'link';
            $info['field_content'] = 'img';
        }
        $info['field_required'] = 0;
        $info['field_display'] = 0;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData9 = $this->checklistStructure($info);
        unset($info);

        $info['group_name'] = 'personal Details';
        $info['customer_type'] = 'co-applicant';
        // $info['group_display'] = 0;
        $info['name'] = 'pan validation';
        $info['key'] = 'pan_validation';
        if($co_pan_info != ''){
            $info['value'] = $co_pan_info;
            $info['field_type'] = 'input';
            $info['field_content'] = 'button';
        }else{
            $info['value'] = $file_path['co_pan_validation'] ?? '';
            $info['field_type'] = 'link';
            $info['field_content'] = 'img';
        }
        $info['field_required'] = 0;
        $info['field_display'] = 0;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData3 = $this->checklistStructure($info);
        unset($info);

        $info['group_name'] = 'personal Details';
        $info['customer_type'] = 'applicant';
        // $info['group_display'] = 1;
        $info['name'] = 'live Photo';
        $info['key'] = !empty($file_path['self_attested_selfie']) ? 'self_attested_selfie' : 'customer_photo';
        $info['value'] = !empty($file_path['self_attested_selfie']) ? $file_path['self_attested_selfie'] : ($file_path['customer_photo'] ?? '');
        $info['field_type'] = 'link';
        // $info['field_content'] = 'image';
        $info['field_accept_value'] = 'application/pdf, image/*';
        $info['field_required'] = 0;
        $info['field_display'] = 0;
        $info['field_value'] = '#';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData10 = $this->checklistStructure($info);
        $document_type = !empty($file_path['self_attested_selfie']) ? "self_attested_selfie" : "customer_photo";
        // if($this->checkEligibilityForDocumentVerification($data['consumer_applications'])){
            $docStatus = $this->checkDocumentStatus($data['consumer_applications']->id, $document_type);
            if ($docStatus == "0"){
                $checklistData10['personal Details']['section']['section_name'][$info['key']]['applicant']['content']['value'] = "";
            } else if ($docStatus == "1" && $docVerificationPermission) {
                $checklistData10['personal Details']['section']['section_name'][$info['key']]['applicant']['content']['verify_document'] = true;
            }
        unset($info);
        $info['group_name'] = 'personal Details';
        $info['customer_type'] = 'co-applicant';
        // $info['group_display'] = 1;
        $info['name'] = 'live photo';
        $info['key'] = !empty($file_path['self_attested_selfie']) ? 'self_attested_selfie' : 'customer_photo';
        $info['value'] = !empty($file_path['self_attested_co_selfie']) ? $file_path['self_attested_co_selfie'] : ($file_path['co_applicant_customer_photo'] ?? '');
        $info['field_type'] = 'link';
        // $info['field_content'] = 'image';
        $info['field_accept_value'] = 'application/pdf, image/*';
        $info['field_required'] = 0;
        $info['field_display'] = 0;
        $info['field_value'] = '#';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData11 = $this->checklistStructure($info);
        $document_type = !empty($file_path['self_attested_co_selfie']) ? "self_attested_co_selfie" : "co_applicant_customer_photo";
        // if($this->checkEligibilityForDocumentVerification($data['consumer_applications'])){
            $docStatus = $this->checkDocumentStatus($data['consumer_applications']->id, $document_type);
            if ($docStatus == "0"){
                $checklistData11['personal Details']['section']['section_name'][$info['key']]['co-applicant']['content']['value'] = "";
            } else if ($docStatus == "1" && $docVerificationPermission) {
                $checklistData11['personal Details']['section']['section_name'][$info['key']]['co-applicant']['content']['verify_document'] = true;
                $checklistData11['personal Details']['section']['section_name'][$info['key']]['co-applicant']['content']['doc_name'] = $document_type;

            }
        unset($info);
        $info['group_name'] = 'personal Details';
        $info['customer_type'] = 'applicant';
        // $info['group_display'] = 1;
        $info['name'] = 'designation';
        $info['key'] = 'designation';
        $info['value'] = $data['consumer_applications']->application_element->designation ?? '';
        $info['field_type'] = 'input';
        $info['field_content'] = 'text';
        $info['field_required'] = 0;
        $info['field_display'] = 0;
        $info['field_value'] = '#';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData12 = $this->checklistStructure($info);
        unset($info);
        $info['group_name'] = 'personal Details';
        $info['customer_type'] = 'co-applicant';
        // $info['group_display'] = 1;
        $info['name'] = 'designation';
        $info['key'] = 'designation';
        $info['value'] = $data['consumer_applications']->application_element->co_applicant_designation ?? '';
        $info['field_type'] = 'input';
        $info['field_content'] = 'text';
        $info['field_required'] = 0;
        $info['field_display'] = 0;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData13 = $this->checklistStructure($info);
        unset($info);
        $info['group_name'] = 'personal Details';
        $info['customer_type'] = 'applicant';
        // $info['group_display'] = 1;
        $info['name'] = 'department';
        $info['key'] = 'department';
        $info['value'] = $data['consumer_applications']->application_element->department ?? '';
        $info['field_type'] = 'input';
        $info['field_content'] = 'text';
        $info['field_required'] = 0;
        $info['field_display'] = 0;
        $info['field_value'] = '#';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData70 = $this->checklistStructure($info);
        unset($info);
        $info['group_name'] = 'personal Details';
        $info['customer_type'] = 'co-applicant';
        // $info['group_display'] = 1;
        $info['name'] = 'department';
        $info['key'] = 'department';
        $info['value'] = '';
        $info['field_type'] = 'input';
        $info['field_content'] = 'text';
        $info['field_required'] = 0;
        $info['field_display'] = 0;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData71 = $this->checklistStructure($info);
        unset($info);

        $negativeArea = $this->getNegativeAreaList($data);
        $isNegativeArea = (isset($application->Checklist->residing) && !empty($application->Checklist->residing)) ? $application->Checklist->residing : ($negativeArea ? $negativeArea : false);

        if($isNegativeArea){
            $negative_area_info = "<a data-list='".json_encode($isNegativeArea, 1)."' class='show_negative_area btn btn-primary col-md-12 btn btn-level-".$isNegativeArea->level."' style='color: white;'>Negative Area</a>";
        }else{
            $negative_area_info = '<div class="d-flex align-content-center justify-content-center"><span>No Negative Area</span></div>';
        }
        $info['group_name'] = 'personal Details';
        $info['customer_type'] = 'applicant';
        // $info['group_display'] = 1;
        $info['name'] = 'negative area';
        $info['key'] = 'negative_area';
        $info['value'] = $negative_area_info;
        $info['field_type'] = 'custom';
        $info['field_content'] = 'file';
        $info['field_required'] = 0;
        $info['field_display'] = 0;
        $info['field_value'] = '#';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData72 = $this->checklistStructure($info);
        unset($info);
        $info['group_name'] = 'personal Details';
        $info['customer_type'] = 'co-applicant';
        // $info['group_display'] = 1;
        $info['name'] = 'negative area';
        $info['key'] = 'negative_area';
        $info['value'] = $negative_area_info;
        $info['field_type'] = 'custom';
        $info['field_content'] = 'file';
        $info['field_required'] = 0;
        $info['field_display'] = 0;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData73 = $this->checklistStructure($info);
        unset($info);
        $info['group_name'] = 'personal Details';
        $info['customer_type'] = 'applicant';
        // $info['group_display'] = 1;
        $info['name'] = 'residing in negative area';
        $info['key'] = 'residing';
        $info['value'] = $isNegativeArea ? '1':'0';
        $info['field_type'] = 'input';
        $info['field_content'] = 'radio';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = [1,0];
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData98 = $this->checklistStructure($info);
        unset($info);
        $info['group_name'] = 'personal Details';
        $info['customer_type'] = 'co-applicant';
        // $info['group_display'] = 1;
        $info['name'] = 'residing in negative area';
        $info['key'] = 'residing';
        $info['value'] = $isNegativeArea ? '1':'0';
        $info['field_type'] = 'input';
        $info['field_content'] = 'radio';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = [1,0];
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData97 = $this->checklistStructure($info);
        unset($info);
        $info['group_name'] = 'personal Details';
        $info['customer_type'] = 'applicant';
        // $info['group_display'] = 1;
        $info['name'] = 'linkedin';
        $info['key'] = 'linkedin';
        $info['value'] = $data['consumer_applications']->Checklist->linkedin ?? '';
        $info['field_type'] = 'input';
        $info['field_content'] = 'text';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = '#';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData74 = $this->checklistStructure($info);
        unset($info);
        $info['group_name'] = 'personal Details';
        $info['customer_type'] = 'co-applicant';
        // $info['group_display'] = 1;
        $info['name'] = 'linkedin';
        $info['key'] = 'linkedin';
        $info['value'] = '';
        $info['field_type'] = 'input';
        $info['field_content'] = 'text';
        $info['field_required'] = 0;
        $info['field_display'] = 0;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData75 = $this->checklistStructure($info);
        unset($info);
        //$info['group_name'] = 'personal Details';
        //$info['customer_type'] = 'applicant';
        // $info['group_display'] = 1;
        //$info['name'] = 'facebook';
        //$info['key'] = 'facebook';
        //$info['value'] = $data['consumer_applications']->Checklist->facebook ?? '';
        //$info['field_type'] = 'input';
        //$info['field_content'] = 'text';
        //$info['field_required'] = 0;
        //$info['field_display'] = 1;
        //$info['field_value'] = '#';
        //$info['content_display'] = 1;
        //$info['checklist_page'] = 'disbursement';
        //$checklistData76 = $this->checklistStructure($info);
        //unset($info);
        $info['group_name'] = 'personal Details';
        $info['customer_type'] = 'co-applicant';
        // $info['group_display'] = 1;
        $info['name'] = 'facebook';
        $info['key'] = 'facebook';
        $info['value'] = '';
        $info['field_type'] = 'input';
        $info['field_content'] = 'text';
        $info['field_required'] = 0;
        $info['field_display'] = 0;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData77 = $this->checklistStructure($info);
        unset($info);

        $courierInfo = (new CouriersController(new Request()))->getCourier($id, 2);
        $courierContent = '<div class="btn btn-primary col-md-12"><a style="color: white;text-decoration: none;" target="_blank" href="/admin/consumer-applications/edit/'.$id.'">View Courier</a></div>';
        $info['group_name'] = 'personal Details';
        $info['customer_type'] = 'applicant';
        // $info['group_display'] = 1;
        $info['name'] = 'courier';
        $info['key'] = 'courier';
        $info['value'] = count($courierInfo) > 0 ? $courierContent : '';
        // $info['default_error'] = 'Courier Not Found';
        $info['field_type'] = 'custom';
        $info['field_content'] = 'button';
        $info['field_required'] = 0;
        $info['field_display'] = 0;
        $info['field_value'] = '#';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData78 = $this->checklistStructure($info);
        unset($info);
        $info['group_name'] = 'personal Details';
        $info['customer_type'] = 'co-applicant';
        // $info['group_display'] = 1;
        $info['name'] = 'courier';
        $info['key'] = 'courier';
        $info['value'] = '';
        $info['field_type'] = 'input';
        $info['field_content'] = 'text';
        $info['field_required'] = 0;
        $info['field_display'] = 0;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData79 = $this->checklistStructure($info);
        unset($info);
        $info['group_name'] = 'personal Details';
        $info['customer_type'] = 'applicant';
        // $info['group_display'] = 1;
        $info['name'] = 'pan card';
        $info['key'] = 'pan_card';
        $info['value'] = $file_path['pan_card'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'img';
        $info['field_required'] = 0;
        $info['field_display'] = 0;
        $info['field_value'] = '#';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData80 = $this->checklistStructure($info);
        unset($info);
        $info['group_name'] = 'personal Details';
        $info['customer_type'] = 'co-applicant';
        // $info['group_display'] = 1;
        $info['name'] = 'pan card';
        $info['key'] = 'pan_card';
        $info['value'] = $file_path['co_pan_card'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'img';
        $info['field_required'] = 0;
        $info['field_display'] = 0;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData81 = $this->checklistStructure($info);
        unset($info);
        $info['group_name'] = 'personal Details';
        $info['customer_type'] = 'applicant';
        // $info['group_display'] = 1;
        $info['name'] = 'aadhar card front';
        $info['key'] = 'aadhar_front';
        $info['value'] = $file_path['aadhar_card'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'img';
        $info['field_required'] = 0;
        $info['field_display'] = 0;
        $info['field_value'] = '#';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData82 = $this->checklistStructure($info);
        unset($info);
        $info['group_name'] = 'personal Details';
        $info['customer_type'] = 'co-applicant';
        // $info['group_display'] = 1;
        $info['name'] = 'aadhar card front';
        $info['key'] = 'aadhar_front';
        $info['value'] = $file_path['co_aadhar_card'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'img';
        $info['field_required'] = 0;
        $info['field_display'] = 0;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData83 = $this->checklistStructure($info);
        unset($info);
        $info['group_name'] = 'personal Details';
        $info['customer_type'] = 'applicant';
        // $info['group_display'] = 1;
        $info['name'] = 'aadhar card back';
        $info['key'] = 'aadhar_back';
        $info['value'] = $file_path['aadhar_card_back'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'img';
        $info['field_required'] = 0;
        $info['field_display'] = 0;
        $info['field_value'] = '#';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData84 = $this->checklistStructure($info);
        unset($info);
        $info['group_name'] = 'personal Details';
        $info['customer_type'] = 'co-applicant';
        // $info['group_display'] = 1;
        $info['name'] = 'aadhar card back';
        $info['key'] = 'aadhar_back';
        $info['value'] = $file_path['co_aadhar_card_back'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'img';
        $info['field_required'] = 0;
        $info['field_display'] = 0;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData85 = $this->checklistStructure($info);
        unset($info);

        if($data['consumer_applications']->application_element && !empty($data['consumer_applications']->application_element->product_name) &&
            $data['consumer_applications']->products && count($data['consumer_applications']->products) > 0){
            $appl_prod = explode(',', $data['consumer_applications']->application_element->product_name);
            $products = Products::whereIn('id', $appl_prod)->get(['name','amount']);

            $data['product_details'] = $products;
            $amount = 0;
            $productName = null;
            foreach($products as $product){
                $amount += $product->amount;
                $productName .= $product->name.',';
            }
            if($amount >= $data['consumer_applications']['loan_amount'] || $amount == 0){
                $product_verified = '1';
            }else{
                $product_verified = '0';
            }
        }

        $productInfo['product_name'] = ($productName ?? $data['consumer_applications']->application_element->product_name) ?? '';
        $productInfo['product_value'] = $amount ?? '';
        $productInfo['merchant_name'] = $data['consumer_applications']->merchant->merchant_name ?? '' ;
        $productInfo['category_name'] = $data['consumer_applications']->category->name ?? '' ;
        if(in_array($data['consumer_applications']->category->id, [6,24])){
            $productInfo['kw_installation'] = ($data['consumer_applications']->application_element->inverter_KW_installation ?? 0).'KW' ;
        }


        $info['group_name'] = 'Product Verification';
        $info['customer_type'] = 'applicant';
        // $info['group_display'] = 1;
        $info['name'] = 'Product details';
        $info['key'] = 'product_info';
        $info['value'] = $productInfo['product_name'] ? $productInfo : '';
        $info['field_type'] = 'box';
        $info['field_content'] = 'box';
        $info['field_required'] = 0;
        $info['field_display'] = 0;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData15 = $this->checklistStructure($info);
        unset($info);

        $product_reason = $this->AcceptableDataReason('product_verification',$data['consumer_applications']);

        $info['group_name'] = 'Product Verification';
        $info['customer_type'] = 'applicant';
        // $info['group_display'] = 1;
        $info['name'] = 'loan amount < product amount';
        $info['key'] = '';
        $info['key_1'] = 'product_status';
        $info['key_2'] = 'product_verification_reason';
        $info['value'] = '';
        $info['value_1'] = $product_verified ?? '0';
        $info['value_2'] = $product_reason ?? '';
        $info['field_type'] = 'ui_small_table';
        $info['field_content'] = 'input';
        $info['field_accessibility_1'] = 'style="pointer-events:none"';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = '';
        $info['field_value_1'] = [1,0];
        $info['field_value_2'] = '';
        $data['field_misc'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData19 = $this->checklistStructure($info);
        unset($info);

        $mandatory_document_logs = MandatoryDocumentListLogs::with('user:id,name')->where('application_id', $id)->orderBy('created_at', 'asc')->get(['id','mandatory_document_list', 'created_at','user_id'])->toArray();

        foreach($mandatory_document_logs as $index => $content){
            unset($mandatory_document_logs[$index]['user']['id']);
            $mandatory_document_logs[$index]['user'][' '] = $mandatory_document_logs[$index]['user']['name'];
            unset($mandatory_document_logs[$index]['user']['name']);
            $j=0;
            $recent_list = [];
            $previous_list = [];
            if($index == 0){
                $recent_list = explode(',', str_replace(['Added ','Removed '],'',$mandatory_document_logs[$index]['mandatory_document_list']));
                $previous_list = [];
                $difference =  array_diff($recent_list, $previous_list);
                $final = (implode(',',$difference));
            }else{
                $j = ($index -1);
                $previous_list = explode(',', str_replace(['Added ','Removed '],'',$mandatory_document_logs[$j]['mandatory_document_list']));
                $recent_list = explode(',', str_replace(['Added ','Removed '],'',$mandatory_document_logs[$index]['mandatory_document_list']));
                $difference = array_diff($recent_list, $previous_list);
                if(count($recent_list) > count($previous_list)){
                    $difference =  array_diff($recent_list, $previous_list);
                }else{
                    $difference =  array_diff($previous_list, $recent_list);
                }
                $final = (implode(',',$difference));
            }
            if((count($recent_list) > count($previous_list))){
                $mandatory_document_logs[$index]['mandatory_document_list'] = 'Added '.$final ;
            }elseif($final){
                $mandatory_document_logs[$index]['mandatory_document_list'] = 'Removed '.$final ;
            }
        }

        $info['group_name'] = 'mandatory document logs';
        $info['customer_type'] = 'applicant';
        $info['group_display'] = count($mandatory_document_logs) ? 1 : 0;
        $info['name'] = '';
        $info['key'] = '';
        $info['value'] = $mandatory_document_logs;
        $info['field_type'] = 'other';
        $info['field_content'] = 'table';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = '';
        // $info['section_name'] = 'logger';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $info['misc_content'] = ['id','mandatory_document_list', 'created_at','user','name'];
        $checklistData16 = $this->checklistStructure($info);
        unset($info);

        $applicationChangeLogs = ($data['consumer_applications']->logger)->toArray();

        foreach($applicationChangeLogs as $index => $content){
            unset($applicationChangeLogs[$index]['user']['id']);
            $applicationChangeLogs[$index]['user'][' '] = $applicationChangeLogs[$index]['user']['name'];
            unset($applicationChangeLogs[$index]['user']['name']);
            $jsonData = json_decode($applicationChangeLogs[$index]['data']);
            foreach($jsonData as $key => $value){
                $applicationChangeLogs[$index]['data'] = ['fieldChange' => ucwords(str_replace('_',' ',$key)), 'oldData' => $value->old, 'newData' => $value->new];
            }
        }

        $info['group_name'] = 'post approval change logs';
        $info['customer_type'] = 'applicant';
        $info['group_display'] = count($applicationChangeLogs) > 0 ? 1 : 0;
        $info['name'] = '';
        $info['key'] = '';
        $info['value'] = $applicationChangeLogs;
        $info['field_type'] = 'other';
        $info['field_content'] = 'table';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = '';
        // $info['section_name'] = 'logs';
        $info['field_misc'] = [];
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $info['misc_content'] = ['id','application_id','data','status','created_at','fieldChange','oldData','newData','user','name'];
        $checklistData17 = $this->checklistStructure($info);
        unset($info);


        $defaultList = ['cpv','repayment history','latest bureau','latest bank statement','cam','tfr report pending'];
        $selectedList = [];
        $savedList = json_decode($data['consumer_applications']->application_element->multi_tranche_exception_list, true);

        if(isset($data['consumer_applications']->application_element->multi_tranche_exception_list)){
            foreach($savedList as $exceptionName => $exceptionValue){
                $name = strtolower($exceptionValue['name']);
                if(in_array($name,$defaultList)){
                    array_push($selectedList,$name);
                }else{
                    array_push($selectedList,$name);
                    array_push($defaultList,$name);
                }
            }
        }

        $info['group_name'] = 'Disbursement List For Multi-Tranche';
        $info['customer_type'] = 'applicant';
        // $info['group_display'] = 1;
        $info['name'] = 'multi-tranche exception list';
        $info['key'] = 'multi_tranche_exception_list';
        $info['value'] = $selectedList;
        $info['field_type'] = 'input';
        $info['field_content'] = 'checkbox';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = $defaultList;
        // $info['section_name'] = 'logs';
        $info['additional_field_key'] = 'multi_tranche_exception_remark';
        $info['additional_field_display'] = 1;
        $info['additional_field_placeholder'] = "Enter name to add above exception list here";
        $info['field_misc'] = [];
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData90 = $this->checklistStructure($info);
        unset($info);

        $k = 0;
        $dtar = [];
        $mandDocResult = array();
        if ($data['consumer_applications']->application_element && isset($data['consumer_applications']->application_element->mandatory_document_list) && !empty($data['consumer_applications']->application_element->mandatory_document_list)) {
            $mandatory_doc_list = explode(',',$data['consumer_applications']->application_element->mandatory_document_list);
            foreach($mandatory_doc_list as $i => $c){
                ++$k;
                ${"info$k"}['group_name'] = 'Mandatory Documents List';
                ${"info$k"}['customer_type'] = 'applicant';
                // ${"info$k"}['group_display'] = 0;
                ${"info$k"}['name'] = str_replace('_',' ',$c);
                ${"info$k"}['key'] = $c;
                foreach ($data['consumer_applications']->documents as $document) {
                // $docsList[$document->file_type] = $document->file_path;
                    if(str_replace(' ','_',$document->file_type) == $c){
                        ${"info$k"}['value'] = $document->file_path;
                    }
                    if (!isset(${"info$k"}['value'])
                        && in_array(strtolower($c), ['emandate', 'e_mandate', 'e mandate'])
                        && in_array(strtolower($document->file_type), ['emandate', 'e_mandate', 'e mandate'])) {
                        ${"info$k"}['value'] = $document->file_path;
                    }
                }
                ${"info$k"}['field_type'] = 'link';
                ${"info$k"}['field_content'] = 'pdf';
                ${"info$k"}['field_required'] = 1;
                ${"info$k"}['field_display'] = 1;
                ${"info$k"}['field_value'] = '';
                ${"info$k"}['content_display'] = 1;
                ${"info$k"}['checklist_page'] = 'disbursement';
                ${"checklistDataM$k"} = $this->checklistStructure(${"info$k"});
                $dtar[] = array_merge([],${"checklistDataM$k"});
            }

            foreach ($dtar as $array) {
                foreach ($array as $key => $value) {
                    if (is_array($value)) {
                        // Recursively combine sub-arrays
                        if (isset($mandDocResult[$key]) && is_array($mandDocResult[$key])) {

                            $mandDocResult[$key] = $this->concatenateArrays($mandDocResult[$key], $value);
                        } else {

                            $mandDocResult[$key] = $value;
                        }
                    } elseif (array_key_exists($key, $mandDocResult)) {
                        // Key already exists, concatenate the value
                        if(!in_array($key, ['group_status','application_type_status','applicant','co-applicant','group_info'])){
                            $mandDocResult[$key][] = $value;
                        }
                    } else {
                        // Key doesn't exist, add it
                        if(!in_array($key, ['group_status','application_type_status','applicant','co-applicant','group_info'])){
                            $mandDocResult[$key][] = $value;
                        }else{
                            $mandDocResult[$key] = $value;
                        }

                    }
                }
            }
        }

        $karzaApproved = $CoKarzaApproved = false;

        $customerData = KarzaVideoAttribute::where('application_id', $id)->whereNull('deleted_at')->whereIn('applicant_type', [1, 2])->get(['id', 'applicant_type']);
        foreach($customerData as $customer) {
            $customer_webhook = KarzaVideoWebhook::where('karza_id', $customer['id'])->get(['data', 'applicant_type']);
            if($customer['applicant_type'] == 1) {
                foreach($customer_webhook as $key => $value) {
                    $kyc_data = json_decode($value->data);
                    if (isset($kyc_data->actionLog)) {
                        $key = array_search("agent", array_column(json_decode(json_encode($kyc_data->actionLog),TRUE), 'role'));
                        if($key) {
                            $kyc_data->agentId = $kyc_data->actionLog[$key]->agentName;
                        }
                    }
                    $kyc_data->status = $kyc_data->approvedByAgent ?? '';

                    $data['customer_webhook'] = $kyc_data;
                }
                // check if applicant has been approved
                if (self::VKYC_VENDOR == "karza") {
                    $karzaApproved = self::checkKarzaApproved($id, 1);
                }
                if(isset($data['customer_webhook'])){
                    if ($karzaApproved){
                        $data['customer_webhook']->status = "ACCEPTED";
                    }else{
                        $data['customer_webhook']->status = "NOT ACCEPTED BY AUDITOR";
                    }
                }
            }
            if($customer['applicant_type'] == 2) {
                foreach($customer_webhook as $key => $value) {
                    $kyc_data = json_decode($value->data);
                    if (isset($kyc_data->actionLog)) {
                        $key = array_search("agent", array_column(json_decode(json_encode($kyc_data->actionLog),TRUE), 'role'));
                        if($key) {
                            $kyc_data->agentId = $kyc_data->actionLog[$key]->agentName;
                        }
                    }
                    $kyc_data->status = $kyc_data->approvedByAgent ?? '';
                    $data['co_customer_webhook'] = $kyc_data;
                }
                // check if applicant has been approved
                if (self::VKYC_VENDOR == "karza") {
                    $CoKarzaApproved = self::checkKarzaApproved($id, 2);
                }
                if(isset($data['co_customer_webhook'])){
                    if ($CoKarzaApproved){
                        $data['co_customer_webhook']->status = "ACCEPTED";
                    }else{
                        $data['co_customer_webhook']->status = "NOT ACCEPTED BY AUDITOR";
                    }
                }
            }
        }

        $digioVKYCInfo = DigioVKYC::where('application_id', $id)->whereNull('deleted_at')->get(['kyc_journey','kyc_status','applicant_type'])->toArray();

        foreach($digioVKYCInfo as $vkycKey => $vkycValue){
            if($vkycValue['applicant_type'] == 1){
                $data['digioVkyc'] = $vkycValue;
            }else{
                $data['codigioVkyc'] = $vkycValue;
            }
        }

        $info['group_name'] = 'kyc details';
        $info['customer_type'] = 'applicant';
        // $info['group_display'] = 1;
        $info['name'] = 'digio vkyc status';
        $info['key'] = 'digio_vkyc';
        $info['value'] = $data['digioVkyc'] ?? '';
        $info['field_type'] = 'input';
        $info['field_content'] = 'button';
        $info['field_required'] = 0;
        $info['field_display'] = 0;
        $info['field_value'] = '';
        // $info['section_name'] = 'logs';
        $info['field_misc'] = [];
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData152 = $this->checklistStructure($info);
        unset($info);

        $info['group_name'] = 'kyc details';
        $info['customer_type'] = 'co-applicant';
        // $info['group_display'] = 1;
        $info['name'] = 'digio vkyc status';
        $info['key'] = 'digio_vkyc';
        $info['value'] = $data['codigioVkyc'] ?? '';
        $info['field_type'] = 'input';
        $info['field_content'] = 'button';
        $info['field_required'] = 0;
        $info['field_display'] = 0;
        $info['field_value'] = '';
        // $info['section_name'] = 'logs';
        $info['field_misc'] = [];
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData153 = $this->checklistStructure($info);
        unset($info);

        $info['group_name'] = 'kyc details';
        $info['customer_type'] = 'applicant';
        // $info['group_display'] = 1;
        $info['name'] = 'digio vkyc video';
        $info['key'] = 'digio_vkyc_video';
        $info['value'] = $file_path['digio_vkyc_video'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'video';
        $info['field_required'] = 0;
        $info['field_display'] = 0;
        $info['field_value'] = '';
        // $info['section_name'] = 'logs';
        $info['field_misc'] = [];
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData164 = $this->checklistStructure($info);
        unset($info);

        $info['group_name'] = 'kyc details';
        $info['customer_type'] = 'co-applicant';
        // $info['group_display'] = 1;
        $info['name'] = 'digio vkyc video';
        $info['key'] = 'digio_vkyc_video';
        $info['value'] = $file_path['co_digio_vkyc_video'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'video';
        $info['field_required'] = 0;
        $info['field_display'] = 0;
        $info['field_value'] = '';
        // $info['section_name'] = 'logs';
        $info['field_misc'] = [];
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData165 = $this->checklistStructure($info);
        unset($info);

        $info['group_name'] = 'kyc details';
        $info['customer_type'] = 'applicant';
        // $info['group_display'] = 1;
        $info['name'] = 'digio vkyc report';
        $info['key'] = 'digio_vkyc_report';
        $info['value'] = $file_path['digio_vkyc_report'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'img';
        $info['field_required'] = 0;
        $info['field_display'] = 0;
        $info['field_value'] = '';
        // $info['section_name'] = 'logs';
        $info['field_misc'] = [];
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData154 = $this->checklistStructure($info);
        unset($info);

        $info['group_name'] = 'kyc details';
        $info['customer_type'] = 'co-applicant';
        // $info['group_display'] = 1;
        $info['name'] = 'digio vkyc report';
        $info['key'] = 'digio_vkyc_report';
        $info['value'] = $file_path['co_digio_vkyc_report'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'img';
        $info['field_required'] = 0;
        $info['field_display'] = 0;
        $info['field_value'] = '';
        // $info['section_name'] = 'logs';
        $info['field_misc'] = [];
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData155 = $this->checklistStructure($info);
        unset($info);

        $info['group_name'] = 'kyc details';
        $info['customer_type'] = 'applicant';
        // $info['group_display'] = 1;
        $info['name'] = 'karza vkyc status';
        $info['key'] = 'karza_vkyc';
        $info['value'] = $data['customer_webhook']->status ?? '';
        $info['field_type'] = 'custom';
        $info['field_content'] = 'text';
        $info['field_required'] = 0;
        $info['field_display'] = 0;
        $info['field_value'] = '';
        // $info['section_name'] = 'logs';
        $info['field_misc'] = [];
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData52 = $this->checklistStructure($info);
        unset($info);

        $info['group_name'] = 'kyc details';
        $info['customer_type'] = 'co-applicant';
        // $info['group_display'] = 1;
        $info['name'] = 'karza vkyc status';
        $info['key'] = 'karza_vkyc';
        $info['value'] = $data['co_customer_webhook']->status ?? '';
        $info['field_type'] = 'custom';
        $info['field_content'] = 'text';
        $info['field_required'] = 0;
        $info['field_display'] = 0;
        $info['field_value'] = '';
        // $info['section_name'] = 'logs';
        $info['field_misc'] = [];
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData53 = $this->checklistStructure($info);
        unset($info);

        $info['group_name'] = 'kyc details';
        $info['customer_type'] = 'applicant';
        // $info['group_display'] = 1;
        $info['name'] = 'karza vkyc video';
        $info['key'] = 'karza_vkyc_video';
        $info['value'] = $file_path['karza_vkyc_video'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'video';
        $info['field_required'] = 0;
        $info['field_display'] = 0;
        $info['field_value'] = '';
        // $info['section_name'] = 'logs';
        $info['field_misc'] = [];
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData64 = $this->checklistStructure($info);
        unset($info);

        $info['group_name'] = 'kyc details';
        $info['customer_type'] = 'co-applicant';
        // $info['group_display'] = 1;
        $info['name'] = 'karza vkyc video';
        $info['key'] = 'karza_vkyc_video';
        $info['value'] = $file_path['co_karza_vkyc_video'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'video';
        $info['field_required'] = 0;
        $info['field_display'] = 0;
        $info['field_value'] = '';
        // $info['section_name'] = 'logs';
        $info['field_misc'] = [];
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData65 = $this->checklistStructure($info);
        unset($info);

        $info['group_name'] = 'kyc details';
        $info['customer_type'] = 'applicant';
        // $info['group_display'] = 1;
        $info['name'] = 'karza vkyc report';
        $info['key'] = 'karza_vkyc_report';
        $info['value'] = $file_path['karza_vkyc_report'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'img';
        $info['field_required'] = 0;
        $info['field_display'] = 0;
        $info['field_value'] = '';
        // $info['section_name'] = 'logs';
        $info['field_misc'] = [];
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData54 = $this->checklistStructure($info);
        unset($info);

        $info['group_name'] = 'kyc details';
        $info['customer_type'] = 'co-applicant';
        // $info['group_display'] = 1;
        $info['name'] = 'karza vkyc report';
        $info['key'] = 'karza_vkyc_report';
        $info['value'] = $file_path['co_karza_vkyc_report'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'img';
        $info['field_required'] = 0;
        $info['field_display'] = 0;
        $info['field_value'] = '';
        // $info['section_name'] = 'logs';
        $info['field_misc'] = [];
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData55 = $this->checklistStructure($info);
        unset($info);

        $info['group_name'] = 'self attested documents of OSV';
        $info['customer_type'] = 'applicant';
        // $info['group_display'] = 1;
        $info['name'] = 'Self Attested Pan (POI)';
        $info['key'] = 'self_attested_pan';
        $info['value'] = $file_path['self_attested_pan'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'img';
        $info['field_required'] = 0;
        $info['field_display'] = 0;
        $info['field_value'] = '';
        // $info['section_name'] = 'logs';
        $info['field_misc'] = [];
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData56 = $this->checklistStructure($info);
        $document_type = "self_attested_pan";
        // if($this->checkEligibilityForDocumentVerification($data['consumer_applications'])){
            $docStatus = $this->checkDocumentStatus($data['consumer_applications']->id, $document_type);
            if ($docStatus == "0"){
                $checklistData56['self attested documents of OSV']['section']['section_name'][$info['key']]['applicant']['content']['value'] = "";
            } else if ($docStatus == "1" && $docVerificationPermission) {
                $checklistData56['self attested documents of OSV']['section']['section_name'][$info['key']]['applicant']['content']['verify_document'] = true;
            }
        // }
        unset($info);

        $info['group_name'] = 'self attested documents of OSV';
        $info['customer_type'] = 'co-applicant';
        // $info['group_display'] = 1;
        $info['name'] = 'Self Attested Pan (POI)';
        $info['key'] = 'self_attested_pan';
        $info['value'] = $file_path['self_attested_co_pan'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'img';
        $info['field_required'] = 0;
        $info['field_display'] = 0;
        $info['field_value'] = '';
        // $info['section_name'] = 'logs';
        $info['field_misc'] = [];
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData57 = $this->checklistStructure($info);
        $document_type = "self_attested_co_pan";
        // if($this->checkEligibilityForDocumentVerification($data['consumer_applications'])){
            $docStatus = $this->checkDocumentStatus($data['consumer_applications']->id, $document_type);
            if ($docStatus == "0"){
                $checklistData57['self attested documents of OSV']['section']['section_name'][$info['key']]['co-applicant']['content']['value'] = "";
            } else if ($docStatus == "1" && $docVerificationPermission) {
                $checklistData57['self attested documents of OSV']['section']['section_name'][$info['key']]['co-applicant']['content']['verify_document'] = true;
                $checklistData57['self attested documents of OSV']['section']['section_name'][$info['key']]['co-applicant']['content']['doc_name'] = $document_type;

            }
        // }
        unset($info);
        $info['group_name'] = 'self attested documents of OSV';
        $info['customer_type'] = 'applicant';
        // $info['group_display'] = 1;
        $info['name'] = 'Self Attested Aadhar (POA)';
        $info['key'] = 'self_attested_aadhar';
        $info['value'] = $file_path['self_attested_aadhar'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'img';
        $info['field_required'] = 0;
        $info['field_display'] = 0;
        $info['field_value'] = '';
        // $info['section_name'] = 'logs';
        $info['field_misc'] = [];
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData58 = $this->checklistStructure($info);
        $document_type = "self_attested_aadhar";
        // if($this->checkEligibilityForDocumentVerification($data['consumer_applications'])){
            $docStatus = $this->checkDocumentStatus($data['consumer_applications']->id, $document_type);
            if ($docStatus == "0"){
                $checklistData58['self attested documents of OSV']['section']['section_name'][$info['key']]['applicant']['content']['value'] = "";
            } else if ($docStatus == "1" && $docVerificationPermission) {
                $checklistData58['self attested documents of OSV']['section']['section_name'][$info['key']]['applicant']['content']['verify_document'] = true;
            }
        // }
        unset($info);

        $info['group_name'] = 'self attested documents of OSV';
        $info['customer_type'] = 'co-applicant';
        // $info['group_display'] = 1;
        $info['name'] = 'Self Attested Aadhar (POA)';
        $info['key'] = 'self_attested_aadhar';
        $info['value'] = $file_path['self_attested_co_aadhar'] ?? '';
        $info['field_type'] = 'link';
        $info['field_content'] = 'img';
        $info['field_required'] = 0;
        $info['field_display'] = 0;
        $info['field_value'] = '';
        // $info['section_name'] = 'logs';
        $info['field_misc'] = [];
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData59 = $this->checklistStructure($info);
        $document_type = "self_attested_co_aadhar";
        // if($this->checkEligibilityForDocumentVerification($data['consumer_applications'])){
            $docStatus = $this->checkDocumentStatus($data['consumer_applications']->id, $document_type);
            if ($docStatus == "0"){
                $checklistData59['self attested documents of OSV']['section']['section_name'][$info['key']]['co-applicant']['content']['value'] = "";
            } else if ($docStatus == "1" && $docVerificationPermission) {
                $checklistData59['self attested documents of OSV']['section']['section_name'][$info['key']]['co-applicant']['content']['verify_document'] = true;
                $checklistData59['self attested documents of OSV']['section']['section_name'][$info['key']]['co-applicant']['content']['doc_name'] = $document_type;

            }
        // }
        unset($info);
        $info['group_name'] = 'self attested documents of OSV';
        $info['customer_type'] = 'applicant';
        // $info['group_display'] = 1;
        $info['name'] = 'self attested aadhar back';
        $info['key'] = 'self_attested_aadhar_back';
        $info['value'] = $file_path['aadhar_card_back'] ?? ''; // TODO Currently set to available file type
        $info['field_type'] = 'link';
        $info['field_content'] = 'img';
        $info['field_required'] = 0;
        $info['field_display'] = 0;
        $info['field_value'] = '';
        // $info['section_name'] = 'logs';
        $info['field_misc'] = [];
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData60 = $this->checklistStructure($info);
        $document_type = "aadhar_card_back";
        // if($this->checkEligibilityForDocumentVerification($data['consumer_applications'])){
            // $docStatus = $this->checkDocumentStatus($data['consumer_applications']->id, $document_type);
            // if ($docStatus == "0"){
            //     $checklistData60['self attested documents of OSV']['section']['section_name'][$info['key']]['applicant']['content']['value'] = "";
            // } else if ($docStatus == "1" && $docVerificationPermission) {
            //     $checklistData60['self attested documents of OSV']['section']['section_name'][$info['key']]['applicant']['content']['verify_document'] = true;
            // }
        // }
        unset($info);

        $info['group_name'] = 'self attested documents of OSV';
        $info['customer_type'] = 'co-applicant';
        // $info['group_display'] = 1;
        $info['name'] = 'self attested aadhar back';
        $info['key'] = 'self_attested_aadhar_back';
        $info['value'] = $file_path['co_applicant_aadhar_card_back'] ?? ''; // TODO Currently set to available file type
        $info['field_type'] = 'link';
        $info['field_content'] = 'img';
        $info['field_required'] = 0;
        $info['field_display'] = 0;
        $info['field_value'] = '';
        // $info['section_name'] = 'logs';
        $info['field_misc'] = [];
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData61 = $this->checklistStructure($info);
        $document_type = "co_applicant_aadhar_card_back";
        // if($this->checkEligibilityForDocumentVerification($data['consumer_applications'])){
            // $docStatus = $this->checkDocumentStatus($data['consumer_applications']->id, $document_type);
            // if ($docStatus == "0"){
            //     $checklistData61['self attested documents of OSV']['section']['section_name'][$info['key']]['co-applicant']['content']['value'] = "";
            // } else if ($docStatus == "1" && $docVerificationPermission) {
            //     $checklistData61['self attested documents of OSV']['section']['section_name'][$info['key']]['co-applicant']['content']['verify_document'] = true;
            //     $checklistData61['self attested documents of OSV']['section']['section_name'][$info['key']]['co-applicant']['content']['doc_name'] = $document_type;
            // }
        // }
        unset($info);
        $checklistData351 = [];
        if($file_path['voter_id'] ?? ''){
            $info['group_name'] = 'self attested documents of OSV';
            $info['customer_type'] = 'applicant';
            $info['name'] = 'Voter id';
            $info['key'] = 'voter_id';
            $info['value'] = $file_path['voter_id'] ?? '';
            $info['field_type'] = 'link';
            $info['field_content'] = 'pdf';
            $info['field_required'] = 0;
            $info['field_display'] = 0;
            $info['field_value'] = '';
            $info['field_misc'] = [];
            $info['content_display'] = 1;
            $info['checklist_page'] = 'disbursement';
            $checklistData351 = $this->checklistStructure($info);
            unset($info);
        }
        $checklistData352 = [];
        if($file_path['passport'] ?? ''){
            $info['group_name'] = 'self attested documents of OSV';
            $info['customer_type'] = 'applicant';
            $info['name'] = 'Passport';
            $info['key'] = 'passport';
            $info['value'] = $file_path['passport'] ?? '';
            $info['field_type'] = 'link';
            $info['field_content'] = 'pdf';
            $info['field_required'] = 0;
            $info['field_display'] = 0;
            $info['field_value'] = '';
            $info['field_misc'] = [];
            $info['content_display'] = 1;
            $info['checklist_page'] = 'disbursement';
            $checklistData352 = $this->checklistStructure($info);
            unset($info);
        }
        $checklistData353 = [];
        if($file_path['visa_copy'] ?? ''){
            $info['group_name'] = 'self attested documents of OSV';
            $info['customer_type'] = 'applicant';
            $info['name'] = 'Visa copy';
            $info['key'] = 'visa_copy';
            $info['value'] = $file_path['visa_copy'] ?? '';
            $info['field_type'] = 'link';
            $info['field_content'] = 'pdf';
            $info['field_required'] = 0;
            $info['field_display'] = 0;
            $info['field_value'] = '';
            $info['field_misc'] = [];
            $info['content_display'] = 1;
            $info['checklist_page'] = 'disbursement';
            $checklistData353 = $this->checklistStructure($info);
            unset($info);
        }
        $checklistData354 = [];
        if($file_path['driving_license'] ?? ''){
            $info['group_name'] = 'self attested documents of OSV';
            $info['customer_type'] = 'applicant';
            $info['name'] = 'Driving License';
            $info['key'] = 'driving_license';
            $info['value'] = $file_path['driving_license'] ?? '';
            $info['field_type'] = 'link';
            $info['field_content'] = 'pdf';
            $info['field_required'] = 0;
            $info['field_display'] = 0;
            $info['field_value'] = '';
            $info['field_misc'] = [];
            $info['content_display'] = 1;
            $info['checklist_page'] = 'disbursement';
            $checklistData354 = $this->checklistStructure($info);
            unset($info);
        }
        $checklistData355 = [];
        if($file_path['mnrega_job_card'] ?? ''){
            $info['group_name'] = 'self attested documents of OSV';
            $info['customer_type'] = 'applicant';
            $info['name'] = 'MNREGA Job Card';
            $info['key'] = 'mnrega_job_card';
            $info['value'] = $file_path['mnrega_job_card'] ?? '';
            $info['field_type'] = 'link';
            $info['field_content'] = 'pdf';
            $info['field_required'] = 0;
            $info['field_display'] = 0;
            $info['field_value'] = '';
            $info['field_misc'] = [];
            $info['content_display'] = 1;
            $info['checklist_page'] = 'disbursement';
            $checklistData355 = $this->checklistStructure($info);
            unset($info);
        }

        $checklistData356 = [];
        if($file_path['Letter_Issued_by_National_Population_register'] ?? ''){
            $info['group_name'] = 'self attested documents of OSV';
            $info['customer_type'] = 'applicant';
            $info['name'] = 'Letter Issued by National Population register';
            $info['key'] = 'Letter_Issued_by_National_Population_register';
            $info['value'] = $file_path['Letter_Issued_by_National_Population_register'] ?? '';
            $info['field_type'] = 'link';
            $info['field_content'] = 'pdf';
            $info['field_required'] = 0;
            $info['field_display'] = 0;
            $info['field_value'] = '';
            $info['field_misc'] = [];
            $info['content_display'] = 1;
            $info['checklist_page'] = 'disbursement';
            $checklistData356 = $this->checklistStructure($info);
            unset($info);
        }
        $checklistData357 = [];
        if($file_path['pg_self_attested_aadhar_card_1'] ?? ''){
            $info['group_name'] = 'self attested documents of OSV';
            $info['customer_type'] = 'applicant';
            $info['name'] = 'PG self attested Aadhar card 1';
            $info['key'] = 'PG self attested Aadhar card 1';
            $info['value'] = $file_path['pg_self_attested_aadhar_card_1'] ?? '';
            $info['field_type'] = 'link';
            $info['field_content'] = 'pdf';
            $info['field_required'] = 0;
            $info['field_display'] = 0;
            $info['field_value'] = '';
            $info['field_misc'] = [];
            $info['content_display'] = 1;
            $info['checklist_page'] = 'disbursement';
            $checklistData357 = $this->checklistStructure($info);
            unset($info);
        }
        $checklistData358 = [];
        if($file_path['pg_self_attested_pan_card_1'] ?? ''){
            $info['group_name'] = 'self attested documents of OSV';
            $info['customer_type'] = 'applicant';
            $info['name'] = 'PG self attested Pan card 1';
            $info['key'] = 'PG self attested Pan card 1';
            $info['value'] = $file_path['pg_self_attested_pan_card_1'] ?? '';
            $info['field_type'] = 'link';
            $info['field_content'] = 'pdf';
            $info['field_required'] = 0;
            $info['field_display'] = 0;
            $info['field_value'] = '';
            $info['field_misc'] = [];
            $info['content_display'] = 1;
            $info['checklist_page'] = 'disbursement';
            $checklistData358 = $this->checklistStructure($info);
            unset($info);
        }
        $checklistData359 = [];
        if($file_path['pg_self_attested_aadhar_card_2'] ?? ''){
            $info['group_name'] = 'self attested documents of OSV';
            $info['customer_type'] = 'applicant';
            $info['name'] = 'PG self attested Aadhar card 2';
            $info['key'] = 'PG self attested Aadhar card 2';
            $info['value'] = $file_path['pg_self_attested_aadhar_card_2'] ?? '';
            $info['field_type'] = 'link';
            $info['field_content'] = 'pdf';
            $info['field_required'] = 0;
            $info['field_display'] = 0;
            $info['field_value'] = '';
            $info['field_misc'] = [];
            $info['content_display'] = 1;
            $info['checklist_page'] = 'disbursement';
            $checklistData359 = $this->checklistStructure($info);
            unset($info);
        }
        $checklistData360 = [];
        if($file_path['pg_self_attested_pan_card_2'] ?? ''){
            $info['group_name'] = 'self attested documents of OSV';
            $info['customer_type'] = 'applicant';
            $info['name'] = 'PG self attested Pan card 2';
            $info['key'] = 'PG self attested Pan card 2';
            $info['value'] = $file_path['pg_self_attested_pan_card_2'] ?? '';
            $info['field_type'] = 'link';
            $info['field_content'] = 'pdf';
            $info['field_required'] = 0;
            $info['field_display'] = 0;
            $info['field_value'] = '';
            $info['field_misc'] = [];
            $info['content_display'] = 1;
            $info['checklist_page'] = 'disbursement';
            $checklistData360 = $this->checklistStructure($info);
            unset($info);
        }
        $checklistData361 =[];
        if($file_path['pg_self_attested_aadhar_card_3'] ?? ''){
            $info['group_name'] = 'self attested documents of OSV';
            $info['customer_type'] = 'applicant';
            $info['name'] = 'PG self attested Aadhar card 3';
            $info['key'] = 'PG self attested Aadhar card 3';
            $info['value'] = $file_path['pg_self_attested_aadhar_card_3'] ?? '';
            $info['field_type'] = 'link';
            $info['field_content'] = 'pdf';
            $info['field_required'] = 0;
            $info['field_display'] = 0;
            $info['field_value'] = '';
            $info['field_misc'] = [];
            $info['content_display'] = 1;
            $info['checklist_page'] = 'disbursement';
            $checklistData361 = $this->checklistStructure($info);
            unset($info);   
        }
        $checklistData362 = [];
        if($file_path['pg_self_attested_pan_card_3'] ?? ''){
            $info['group_name'] = 'self attested documents of OSV';
            $info['customer_type'] = 'applicant';
            $info['name'] = 'PG self attested Pan card 3';
            $info['key'] = 'PG self attested Pan card 3';
            $info['value'] = $file_path['pg_self_attested_pan_card_3'] ?? '';
            $info['field_type'] = 'link';
            $info['field_content'] = 'pdf';
            $info['field_required'] = 0;
            $info['field_display'] = 0;
            $info['field_value'] = '';
            $info['field_misc'] = [];
            $info['content_display'] = 1;
            $info['checklist_page'] = 'disbursement';
            $checklistData362 = $this->checklistStructure($info);
            unset($info);
        }
        $checklistData363 = [];
        if($file_path['owner_self_attested_pan_card_1'] ?? ''){
            $info['group_name'] = 'self attested documents of OSV';
            $info['customer_type'] = 'applicant';
            $info['name'] = 'Owner self attested Pan card 1';
            $info['key'] = 'Owner self attested Pan card 1';
            $info['value'] = $file_path['owner_self_attested_pan_card_1'] ?? '';
            $info['field_type'] = 'link';
            $info['field_content'] = 'pdf';
            $info['field_required'] = 0;
            $info['field_display'] = 0;
            $info['field_value'] = '';
            $info['field_misc'] = [];
            $info['content_display'] = 1;
            $info['checklist_page'] = 'disbursement';
            $checklistData363 = $this->checklistStructure($info);
            unset($info);
        }
        $checklistData364 = [];
        if($file_path['owner_self_attested_aadhar_card_1'] ?? ''){
            $info['group_name'] = 'self attested documents of OSV';
            $info['customer_type'] = 'applicant';
            $info['name'] = 'Owner self attested Aadhar card 1';
            $info['key'] = 'Owner self attested Aadhar card 1';
            $info['value'] = $file_path['owner_self_attested_aadhar_card_1'] ?? '';
            $info['field_type'] = 'link';
            $info['field_content'] = 'pdf';
            $info['field_required'] = 0;
            $info['field_display'] = 0;
            $info['field_value'] = '';
            $info['field_misc'] = [];
            $info['content_display'] = 1;
            $info['checklist_page'] = 'disbursement';
            $checklistData364 = $this->checklistStructure($info);
            unset($info);
        }
        $checklistData365 = [];
        if($file_path['self_attested_entity_pan_card'] ?? ''){
            $info['group_name'] = 'self attested documents of OSV';
            $info['customer_type'] = 'applicant';
            $info['name'] = 'Self-attested Entity PAN card';
            $info['key'] = 'Self-attested Entity PAN card';
            $info['value'] = $file_path['self_attested_entity_pan_card'] ?? '';
            $info['field_type'] = 'link';
            $info['field_content'] = 'pdf';
            $info['field_required'] = 0;
            $info['field_display'] = 0;
            $info['field_value'] = '';
            $info['field_misc'] = [];
            $info['content_display'] = 1;
            $info['checklist_page'] = 'disbursement';
            $checklistData365 = $this->checklistStructure($info);
            unset($info);
        }
        $checklistData366 = [];
        if($file_path['self_attested_auth_signatory_1_pan'] ?? ''){
            $info['group_name'] = 'self attested documents of OSV';
            $info['customer_type'] = 'applicant';
            $info['name'] = 'Self-attested Auth signatory 1 PAN';
            $info['key'] = 'Self-attested Auth signatory 1 PAN';
            $info['value'] = $file_path['self_attested_auth_signatory_1_pan'] ?? '';
            $info['field_type'] = 'link';
            $info['field_content'] = 'pdf';
            $info['field_required'] = 0;
            $info['field_display'] = 0;
            $info['field_value'] = '';
            $info['field_misc'] = [];
            $info['content_display'] = 1;
            $info['checklist_page'] = 'disbursement';
            $checklistData366 = $this->checklistStructure($info);
            unset($info);
        }
        $checklistData367 = [];
        if($file_path['self_attested_auth_signatory_2_pan'] ?? ''){
            $info['group_name'] = 'self attested documents of OSV';
            $info['customer_type'] = 'applicant';
            $info['name'] = 'Self-attested Auth signatory 2 PAN';
            $info['key'] = 'Self-attested Auth signatory 2 PAN';
            $info['value'] = $file_path['self_attested_auth_signatory_2_pan'] ?? '';
            $info['field_type'] = 'link';
            $info['field_content'] = 'pdf';
            $info['field_required'] = 0;
            $info['field_display'] = 0;
            $info['field_value'] = '';
            $info['field_misc'] = [];
            $info['content_display'] = 1;
            $info['checklist_page'] = 'disbursement';
            $checklistData367 = $this->checklistStructure($info);
            unset($info);
        }
        $checklistData368 = [];
        if($file_path['self_attested_auth_signatory_1_aadhaar'] ?? ''){
            $info['group_name'] = 'self attested documents of OSV';
            $info['customer_type'] = 'applicant';
            $info['name'] = 'Self-attested Auth signatory 1 Aadhaar';
            $info['key'] = 'Self-attested Auth signatory 1 Aadhaar';
            $info['value'] = $file_path['self_attested_auth_signatory_1_aadhaar'] ?? '';
            $info['field_type'] = 'link';
            $info['field_content'] = 'pdf';
            $info['field_required'] = 0;
            $info['field_display'] = 0;
            $info['field_value'] = '';
            $info['field_misc'] = [];
            $info['content_display'] = 1;
            $info['checklist_page'] = 'disbursement';
            $checklistData368 = $this->checklistStructure($info);
            unset($info);
        }
        $checklistData369 = [];
        if($file_path['self_attested_auth_signatory_2_aadhaar'] ?? ''){
            $info['group_name'] = 'self attested documents of OSV';
            $info['customer_type'] = 'applicant';
            $info['name'] = 'Self-attested Auth signatory 2 Aadhaar';
            $info['key'] = 'Self-attested Auth signatory 2 Aadhaar';
            $info['value'] = $file_path['self_attested_auth_signatory_2_aadhaar'] ?? '';
            $info['field_type'] = 'link';
            $info['field_content'] = 'pdf';
            $info['field_required'] = 0;
            $info['field_display'] = 0;
            $info['field_value'] = '';
            $info['field_misc'] = [];
            $info['content_display'] = 1;
            $info['checklist_page'] = 'disbursement';
            $checklistData369 = $this->checklistStructure($info);
            unset($info);
        }
        $checklistData370 = [];
        if($file_path['self_attested_director_1_pan'] ?? ''){
            $info['group_name'] = 'self attested documents of OSV';
            $info['customer_type'] = 'applicant';
            $info['name'] = 'Self-attested Director 1 PAN';
            $info['key'] = 'Self-attested Director 1 PAN';
            $info['value'] = $file_path['self_attested_director_1_pan'] ?? '';
            $info['field_type'] = 'link';
            $info['field_content'] = 'pdf';
            $info['field_required'] = 0;
            $info['field_display'] = 0;
            $info['field_value'] = '';
            $info['field_misc'] = [];
            $info['content_display'] = 1;
            $info['checklist_page'] = 'disbursement';
            $checklistData370 = $this->checklistStructure($info);
            unset($info);
        }
        $checklistData371 = [];
        if($file_path['self_attested_director_2_pan'] ?? ''){
            $info['group_name'] = 'self attested documents of OSV';
            $info['customer_type'] = 'applicant';
            $info['name'] = 'Self-attested Director 2 PAN';
            $info['key'] = 'Self-attested Director 2 PAN';
            $info['value'] = $file_path['self_attested_director_2_pan'] ?? '';
            $info['field_type'] = 'link';
            $info['field_content'] = 'pdf';
            $info['field_required'] = 0;
            $info['field_display'] = 0;
            $info['field_value'] = '';
            $info['field_misc'] = [];
            $info['content_display'] = 1;
            $info['checklist_page'] = 'disbursement';
            $checklistData371 = $this->checklistStructure($info);
            unset($info);
        }
        $checklistData372 = [];
        if($file_path['self_attested_director_3_pan'] ?? ''){
            $info['group_name'] = 'self attested documents of OSV';
            $info['customer_type'] = 'applicant';
            $info['name'] = 'Self-attested Director 3 PAN';
            $info['key'] = 'Self-attested Director 3 PAN';
            $info['value'] = $file_path['self_attested_director_3_pan'] ?? '';
            $info['field_type'] = 'link';
            $info['field_content'] = 'pdf';
            $info['field_required'] = 0;
            $info['field_display'] = 0;
            $info['field_value'] = '';
            $info['field_misc'] = [];
            $info['content_display'] = 1;
            $info['checklist_page'] = 'disbursement';
            $checklistData372 = $this->checklistStructure($info);
            unset($info);
        }
        $checklistData373 = [];
        if($file_path['self_attested_director_1_aadhaar'] ?? ''){
            $info['group_name'] = 'self attested documents of OSV';
            $info['customer_type'] = 'applicant';
            $info['name'] = 'Self-attested Director 1 Aadhaar';
            $info['key'] = 'Self-attested Director 1 Aadhaar';
            $info['value'] = $file_path['self_attested_director_1_aadhaar'] ?? '';
            $info['field_type'] = 'link';
            $info['field_content'] = 'pdf';
            $info['field_required'] = 0;
            $info['field_display'] = 0;
            $info['field_value'] = '';
            $info['field_misc'] = [];
            $info['content_display'] = 1;
            $info['checklist_page'] = 'disbursement';
            $checklistData373 = $this->checklistStructure($info);
            unset($info);
        }
        $checklistData374 = [];
        if($file_path['self_attested_director_2_aadhaar'] ?? ''){
            $info['group_name'] = 'self attested documents of OSV';
            $info['customer_type'] = 'applicant';
            $info['name'] = 'Self-attested Director 2 Aadhaar';
            $info['key'] = 'Self-attested Director 2 Aadhaar';
            $info['value'] = $file_path['self_attested_director_2_aadhaar'] ?? '';
            $info['field_type'] = 'link';
            $info['field_content'] = 'pdf';
            $info['field_required'] = 0;
            $info['field_display'] = 0;
            $info['field_value'] = '';
            $info['field_misc'] = [];
            $info['content_display'] = 1;
            $info['checklist_page'] = 'disbursement';
            $checklistData374 = $this->checklistStructure($info);
            unset($info);
        }
        $checklistData375 = [];
        if($file_path['self_attested_director_3_aadhaar'] ?? ''){
            $info['group_name'] = 'self attested documents of OSV';
            $info['customer_type'] = 'applicant';
            $info['name'] = 'Self-attested Director 3 Aadhaar';
            $info['key'] = 'Self-attested Director 3 Aadhaar';
            $info['value'] = $file_path['self_attested_director_3_aadhaar'] ?? '';
            $info['field_type'] = 'link';
            $info['field_content'] = 'pdf';
            $info['field_required'] = 0;
            $info['field_display'] = 0;
            $info['field_value'] = '';
            $info['field_misc'] = [];
            $info['content_display'] = 1;
            $info['checklist_page'] = 'disbursement';
            $checklistData375 = $this->checklistStructure($info);
            unset($info);
        }
        

        $digio = KYCDetails::where('application_id', $id)->whereNotNull('response')->orderBy('id','desc')->get(['response', 'applicant_type','created_at']);
        foreach($digio as $kyc){
            if($kyc['applicant_type'] == 2){
                $data['co_app_digio_kyc'] = $kyc;
            }else{
                $data['digio_kyc'] = $kyc;
            }
        }

        $info['group_name'] = 'kyc details';
        $info['customer_type'] = 'applicant';
        // $info['group_display'] = 1;
        $info['name'] = 'digio kyc';
        $info['key'] = 'digio_kyc';
        $info['value'] = (array)($data['digio_kyc'] ?? null);
        $info['field_type'] = 'input';
        $info['field_content'] = 'button';
        $info['field_required'] = 0;
        $info['field_display'] = 0;
        $info['field_value'] = '';
        // $info['section_name'] = 'logs';
        $info['field_misc'] = [];
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';

        $checklistData20 = $this->checklistStructure($info);
        unset($info);

        $info['group_name'] = 'kyc details';
        $info['customer_type'] = 'co-applicant';
        // $info['group_display'] = 1;
        $info['name'] = 'digio kyc';
        $info['key'] = 'digio_kyc';
        $info['value'] = (array)($data['co_app_digio_kyc'] ?? null);
        $info['field_type'] = 'input';
        $info['field_content'] = 'button';
        $info['field_required'] = 0;
        $info['field_display'] = 0;
        $info['field_value'] = '';
        // $info['section_name'] = 'logs';
        $info['field_misc'] = [];
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData21 = $this->checklistStructure($info);
        unset($info);

        $checklistException = ChecklistExceptionLogs::where('application_id',$id)->where('exception_type','bank_exception')->orderby('created_at','desc')->first(['exception']);
        $exceptionRemarksForBank = null;
        if(!empty($checklistException) && !empty($checklistException->exception)){
            $exceptionRemarksForBank = $checklistException->exception;
        }

        $namePercentage = 0;
        $accountPercentage = 0;
        $ifscPercentage = 0;
        $nameBPercentage = 0;
        $accountBPercentage = 0;
        $ifscBPercentage = 0;
        $namePPercentage = 0;
        $accountPPercentage = 0;
        $ifscPPercentage = 0;
        $nameAPercentage = 0;
        $mname = null;
        $maccount = null;
        $mifsc = null;

        if(count($data['consumer_applications']->document_details) > 0){
            foreach($data['consumer_applications']->document_details as $documentInfo){
                if($documentInfo->doc_type == 'MANDATE'){
                    $mapp = json_decode($documentInfo->json_data);
                    $mname = $mapp->debtor_account_name;
                    $maccount = $mapp->debtor_account_number;
                    $mifsc = $mapp->debtor_account_ifsc_code;
                }
            }
        }

        if(isset($data['consumer_applications']->bank_details->karza_response)){
            $karza = json_decode($data['consumer_applications']->bank_details->karza_response);
            if(!empty($karza->result)){
                $pname = $karza->result->accountName ?? null;
                $paccount = $karza->result->accountNumber ?? null;
                $pifsc = $karza->result->ifsc ?? null;
            }else{
                $pname = null;
                $paccount = null;
                $pifsc = null;
            }
        }else{
            $pname = null;
            $paccount = null;
            $pifsc = null;
        }

        $mandate = [
            'name' => $mname,
            'account_number' => $maccount,
            'ifsc' => $mifsc
        ];
        $bank = [
            'name' => $data['consumer_applications']->bank_details->name ?? null,
            'account_number' => $data['consumer_applications']->bank_details->account_number ?? null,
            'ifsc' => $data['consumer_applications']->bank_details->ifsc_code ?? null
        ];
        $peny = [
            'name' => $pname,
            'account_number' => $paccount,
            'ifsc' => $pifsc
        ];

        if($mandate['name'] != null && $mandate['account_number'] != null && $mandate['ifsc'] != null){
            similar_text(strtolower($mandate['name']),strtolower($bank['name']), $nameBPercentage);
            similar_text(strtolower($mandate['account_number']),strtolower($bank['account_number']), $accountBPercentage);
            similar_text(strtolower($mandate['ifsc']),strtolower($bank['ifsc']), $ifscBPercentage);

            similar_text(strtolower($mandate['name']),strtolower($peny['name']), $namePPercentage);
            similar_text(strtolower($mandate['account_number']),strtolower($peny['account_number']), $accountPPercentage);
            similar_text(strtolower($mandate['ifsc']),strtolower($peny['ifsc']), $ifscPPercentage);

            similar_text(strtolower($mandate['name']),strtolower($data['consumer_applications']->name), $nameAPercentage);

            if(round($namePPercentage) < 60){
                $namePPercentage1 = 'false';
            }else{
                $namePPercentage1 = 'true';
            }
            if(round($accountPPercentage) < 100){
                $accountPPercentage1 = 'false';
            }else{
                $accountPPercentage1 = 'true';
            }
            if(round($ifscPPercentage) < 80){
                $ifscPPercentage1 = 'false';
            }else{
                $ifscPPercentage1 = 'true';
            }
        }else{
            similar_text(strtolower($bank['name']),strtolower($peny['name']), $namePercentage);
            similar_text(strtolower($bank['account_number']),strtolower($peny['account_number']), $accountPercentage);
            similar_text(strtolower($bank['ifsc']),strtolower($peny['ifsc']), $ifscPercentage);
            similar_text(strtolower($bank['name']),strtolower($data['consumer_applications']->name), $nameAPercentage);
            if(round($namePercentage) < 60){
                $namePPercentage1 = 'false';
            }else{
                $namePPercentage1 = 'true';
            }
            if(round($accountPercentage) < 100){
                $accountPPercentage1 = 'false';
            }else{
                $accountPPercentage1 = 'true';
            }
            if(round($ifscPercentage) < 80){
                $ifscPPercentage1 = 'false';
            }else{
                $ifscPPercentage1 = 'true';
            }
        }

        if(round($nameBPercentage) < 60){
            $nameBPercentage1 = 'false';
        }else{
            $nameBPercentage1 = 'true';
        }
        if(round($accountBPercentage) < 100){
            $accountBPercentage1 = 'false';
        }else{
            $accountBPercentage1 = 'true';
        }
        if(round($ifscBPercentage) < 80){
            $ifscBPercentage1 = 'false';
        }else{
            $ifscBPercentage1 = 'true';
        }
        if(round($nameAPercentage) < 60){
            $nameAPercentage1 = 'false';
        }else{
            $nameAPercentage1 = 'true';
        }

        if($nameBPercentage1 == 'true' && $accountBPercentage1 == 'true' && $ifscBPercentage1 == 'true' && $namePPercentage1 == 'true' && $nameAPercentage1 == 'true' && $accountPPercentage1 == 'true' && $ifscPPercentage1 == 'true'){
            $totalBankMatchStatus = '<i class="fa fa-check"></i>';
        }else{
            $totalBankMatchStatus = '<i class="fa fa-close" style="color:red"></i>';
        }
        $appName = $data['consumer_applications']->name ?? null;

        $bankMandateMatch = [
            'mandate' => [
                'mname' => ['item'=>$mname,'status'=>''],
                'bName' => ['item'=>$bank['name'],'status'=> $nameBPercentage1== 'true' ? '<i class="fa fa-check"></i>':'<i class="fa fa-close" style="color:red"></i>'],
                'pName' => ['item'=>$peny['name'],'status'=> $namePPercentage1== 'true' ? '<i class="fa fa-check"></i>':'<i class="fa fa-close" style="color:red"></i>'],
                'EName' => ['item'=>$appName,'status'=> $nameAPercentage1== 'true' ? '<i class="fa fa-check"></i>':'<i class="fa fa-close" style="color:red"></i>']
                ],
            'bank' => [
                'maccount' => ['item'=>$maccount,'status'=>''],
                'bAccount' => ['item'=>$bank['account_number'],'status'=> $accountBPercentage1 == 'true' ? '<i class="fa fa-check"></i>':'<i class="fa fa-close" style="color:red"></i>'],
                'pAccount' => ['item'=>$peny['account_number'],'status'=> $accountPPercentage1 == 'true' ? '<i class="fa fa-check"></i>':'<i class="fa fa-close" style="color:red"></i>'],
                'EAccount' => ''
                ],
            'peny' => [
                'mifsc' => ['item'=>$mifsc,'status'=>''],
                'bIfsc' => ['item'=>$bank['ifsc'],'status'=> $ifscBPercentage1 == 'true' ? '<i class="fa fa-check"></i>':'<i class="fa fa-close" style="color:red"></i>'],
                'pIfsc' => ['item'=>$peny['ifsc'],'status'=> $ifscPPercentage1 == 'true' ? '<i class="fa fa-check"></i>':'<i class="fa fa-close" style="color:red"></i>'],
                'EIfsc' => ''
            ],
            'system' => []
        ];
        $dataArray = ['mandate','mname','bName','pName','EName','bank','maccount','bAccount','pAccount','peny','mifsc','bIfsc','pIfsc'];


        $mandateData = Mandate::where('consumer_application_id' ,$id)->whereIn('status' ,['active','submitted','registered'])->orderBy('created_at', 'desc')->first();
        $consumerFiles = ConsumerApplicationFiles::where('consumer_application_id', $id)->wherenull('deleted_at')->where(function ($query) {
            $query->where('file_type', 'like', '%nach%')
            ->orWhere('file_type', 'like', '%mandate%')
            ->orWhere('file_type', 'like', '%emandate%');
        })->get();

        $netAmount = (new \App\Http\Controllers\NachController())->getNetAmountV1($data['consumer_applications']);
        $mandateInfo['net_amount']  = $netAmount > 0 ? $netAmount : 0;
        $mandateInfo['mandate_amount']  = !empty($mandateData) && $mandateData->mandate_amount > 0  ? $mandateData->mandate_amount : 0;
        $mandateInfo['status'] = !empty($mandateData) && $mandateData->mandate_amount == $netAmount ? '<i class="fa fa-check"></i>':'<i class="fa fa-close" style="color:red"></i>';
        $mandateInfo1[0] = $mandateInfo;

        $amountException = ChecklistExceptionLogs::where('application_id',$id)->where('exception_type','mandate_amount_exception')->orderBy('created_at','desc')->first(['exception']);
        $exceptionRemarks1 = null;
        if(!empty($amountException) && !empty($amountException->exception)){
            $exceptionRemarks1 = $amountException->exception;
        }

        $info['group_name'] = 'bank & mandate checklist';
        $info['customer_type'] = 'applicant';
        // $info['group_display'] = 1;
        $info['name'] = '';
        $info['key'] = '';
        $info['value'] = $mandateInfo1;
        $info['field_type'] = 'other';
        $info['field_content'] = 'table';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = '';
        $info['section_name'] = 'mandate amount details';
        $info['section_misc_info'] = $mandateInfo['status'];
        // $info['show_exception_field'] = 1;
        $info['additional_field_name'] = "Exception";
        $info['additional_field_key'] = 'mandate_amount_exception_remarks';
        $info['additional_field_display'] = 1;
        $info['additional_field_type'] = 'select';
        $info['additional_field_value'] = $exceptionRemarks1;
        $info['field_misc'] = [];
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $info['misc_content'] = ['net_amount','mandate_amount','status'];
        $checklistData92 = $this->checklistStructure($info);
        unset($info);

        $mandateUtilityCode = '';
        $mandateCreditorName = '';
        $mandateLastEMIDate = '';
        $mandateDocs = DocumentDetails::where('application_id', $id)->where('doc_type', 'MANDATE')->whereNull('deleted_at')->orderBy('created_at','desc')->first();
        $mandateDetails['mandate_status']['system'] = '';
        $mandateDetails['mandate_status']['mandate_document']  = 'No Data';
        $mandateDetails['mandate_status']['status'] = '<i class="fa fa-close" style="color:red"></i>';
        if (isset($consumerFiles) and count($consumerFiles) > 0) {
            $mandateDetails['mandate_status']['mandate_document']  = 'Active';
            $mandateDetails['mandate_status']['status'] = '<i class="fa fa-check"></i>';
        }
        if (isset($mandateData)) {
            $mandateDetails['mandate_status']['mandate_document']  = !empty($mandateData) && in_array($mandateData->status, ['active','submitted','registered']) ? 'Active' : 'Inactive';
            $mandateDetails['mandate_status']['status'] = !empty($mandateData) && in_array($mandateData->status, ['active','submitted','registered']) ? '<i class="fa fa-check"></i>':'<i class="fa fa-close" style="color:red"></i>';
        }

        if(!empty($mandateDocs)){
            $mandateJsonData = json_decode($mandateDocs->json_data, true);
            $mandateUtilityCode     = !empty($mandateJsonData['creditor_utility_code']) ? $mandateJsonData['creditor_utility_code'] : '';
            $mandateCreditorName    = !empty($mandateJsonData['creditor_name']) ? $mandateJsonData['creditor_name'] : '';
            $mandateLastEMIDate     = !empty($mandateJsonData['date_final_collection']) ? $mandateJsonData['date_final_collection'] : '';
        }

        $document = ConsumerApplicationFiles::where('consumer_application_id', $id)->where('file_type', 'e mandate')->whereNull('deleted_at')->orderBy('created_at','desc')->first(['file_path']);
        $documentPath = !empty($document->file_path) ? $document->file_path : '';
        // $mandateDetails['mandate_document']['mandate_document']  = $documentPath;
        // $mandateDetails['mandate_document']['status'] = !empty($documentPath) ? true : false;
        $data['documentPath'] = $documentPath;

        $utilityCode = !empty($data['consumer_applications']->lender->bank_details) ? $data['consumer_applications']->lender->bank_details->utility_code : '';
        $mandateDetails['mandate_utility_code']['mandate_document']  = $mandateUtilityCode;
        $mandateDetails['mandate_utility_code']['system']  = $utilityCode;
        if(!empty($mandateUtilityCode) && !empty($utilityCode)){
            $mandateDetails['mandate_utility_code']['status'] = trim($mandateUtilityCode) == trim($utilityCode)  ? '<i class="fa fa-check"></i>':'<i class="fa fa-close" style="color:red"></i>';
        }else{
            $mandateDetails['mandate_utility_code']['status'] = '<i class="fa fa-close" style="color:red"></i>';
        }

        $creditorName = !empty($data['consumer_applications']->lender) ? $data['consumer_applications']->lender->name : '';
        $mandateDetails['mandate_creditor_name']['mandate_document']  = $mandateCreditorName;
        $mandateDetails['mandate_creditor_name']['system']  = $creditorName;
        if(!empty($mandateCreditorName) && !empty($creditorName)){
            $mandateDetails['mandate_creditor_name']['status'] = trim($mandateCreditorName) == trim($creditorName)  ? '<i class="fa fa-check"></i>':'<i class="fa fa-close" style="color:red"></i>';
        }else{
            $mandateDetails['mandate_creditor_name']['status'] = '<i class="fa fa-close" style="color:red"></i>';
        }

        $lastEMIDate = $data['consumer_applications']['application_element']['last_emi_date'] ?? '';
        $mandateDetails['mandate_last_emi_date']['system']  = $lastEMIDate;
        $mandateDetails['mandate_last_emi_date']['mandate_document']  = $mandateLastEMIDate;
        $emiStatus = false;
        if(!empty($mandateLastEMIDate) && !empty($lastEMIDate) && $mandateLastEMIDate > $lastEMIDate){
            $emiStatus = true;
        } else if($mandateLastEMIDate == ''){
            $emiStatus = true;
        }
        $mandateDetails['mandate_last_emi_date']['status'] = $emiStatus ? '<i class="fa fa-check"></i>':'<i class="fa fa-close" style="color:red"></i>';

        $mandateArray = [$mandateDetails['mandate_status']['status'],$mandateDetails['mandate_utility_code']['status'],$mandateDetails['mandate_creditor_name']['status'],$mandateDetails['mandate_last_emi_date']['status']];
        if(in_array('<i class="fa fa-close" style="color:red"></i>',$mandateArray)){
            $miscChecklistStatus = '<i class="fa fa-close" style="color:red"></i>';
        }else{
            $miscChecklistStatus = '<i class="fa fa-check"></i>';
        }

        // Mandate miscellaneous - collection emi date check
        $mandateData = Mandate::where('consumer_application_id' ,$id)->where('status','active')->orderBy('created_at', 'desc')->first();
        $collectionEMI['first_collection_date'] = '';
        $collectionEMI['first_emi_date'] = '';
        $collectionEMI['status'] = '';
        $lenderEMI['lender_name'] = '';
        $lenderEMI['emi_date'] = '';
        $lenderEMI['status'] = '';
        if(!empty($mandateData) && $mandateData->status == 'active' && $mandateData->mandate_amount > 0){
            $rawCollectionDate = $mandateData->date_first_collection;
            $collection_date = Carbon::parse($rawCollectionDate)->format('Y-m-d H:i:s');
            $emiCalc = ApplicationEMICalculation::where('application_id',$id)->first();
            $rawEMIDate = !empty($emiCalc) ? $emiCalc->emi_date : '';
            $emiDate = Carbon::parse($rawEMIDate)->format('Y-m-d H:i:s');
            $collectionEMI['first_collection_date'] = substr($emiDate, 0, strrpos($emiDate, ' '));
            $collectionEMI['first_emi_date'] = substr($collection_date, 0, strrpos($collection_date, ' '));
            $collectionEMI['status'] = !empty($collection_date) && !empty($emiDate) && $collection_date == $emiDate ? '<i class="fa fa-check"></i>':'<i class="fa fa-close" style="color:red"></i>';

        // Mandate miscellaneous - lender emi day check
            $emiDate1 = !empty($emiCalc) ? $emiCalc->emi_date : '';
            $lenderEMIDetails = $this->checkLenderEMIDayV1($data['consumer_applications']['lender_id'], $emiDate1);
            $lenderEMI['lender_name'] = !empty($data['consumer_applications']->lender) ? $data['consumer_applications']->lender->name : '';
            $lenderEMI['emi_date'] = !empty($lenderEMIDetails) ? $lenderEMIDetails['day'].''.'th' : '';
            $lenderEMI['status'] = !empty($lenderEMIDetails) && $lenderEMIDetails['status'] ? '<i class="fa fa-check"></i>':'<i class="fa fa-close" style="color:red"></i>';
        }
        $collectionEMI1['lender_collection_date'] = $collectionEMI;
        $lenderEMI1['lender_emi_day'] = $lenderEMI;

        if(in_array('<i class="fa fa-close" style="color:red"></i>',[$totalBankMatchStatus,$mandateInfo['status'],$miscChecklistStatus])){
            $bnm_misc_info = '<i class="fa fa-close" style="color:red"></i>';
        }else{
            $bnm_misc_info = '<i class="fa fa-check"></i>';
        }

        $docException = ChecklistExceptionLogs::where('application_id',$id)->where('exception_type','mandate_document_exception')->orderby('created_at','desc')->first(['exception']);
        $exceptionRemarks = null;
        if(!empty($docException) && !empty($docException->exception)){
            $exceptionRemarks = $docException->exception;
        }

        $info['group_name'] = 'bank & mandate checklist';
        $info['customer_type'] = 'applicant';
        // $info['group_display'] = 1;
        $info['group_misc_info'] = $bnm_misc_info;
        $info['name'] = '';
        $info['key'] = '';
        $info['value'] = $bankMandateMatch;
        // $info['value'] = $r;
        $info['field_type'] = 'other';
        $info['field_content'] = 'table3';
        $info['field_required'] = 0;
        $info['field_display'] = 0;
        $info['field_value'] = '';
        $info['section_name'] = 'bank details';
        $info['section_misc_info'] = $totalBankMatchStatus;
        // $info['show_exception_field'] = 1;
        $info['additional_field_name'] = "Exception";
        $info['additional_field_key'] = 'bank_details_exception';
        $info['additional_field_display'] = 1;
        $info['additional_field_type'] = 'select';
        $info['additional_field_value'] = $exceptionRemarksForBank;
        $info['field_misc'] = [];
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData91 = $this->checklistStructure($info);
        unset($info);


        $info['group_name'] = 'bank & mandate checklist';
        $info['customer_type'] = 'applicant';
        // $info['group_display'] = 1;
        $info['name'] = '';
        $info['key'] = '';
        $info['value'] = [
                ['data' => $collectionEMI1, 'infoHeader' => ['collection_emi','status','value','system_value']],
                ['data' => $lenderEMI1, 'infoHeader' => ['lender_emi','status','value','system_value']],
                ['data' => $mandateDetails, 'infoHeader' => ['mandate_document','mandate_utility_code','mandate_creditor_name','mandate_last_emi_date','status','value','system','mandate_document']],
        ];
        $info['multi_table'] = 1;
        $info['field_type'] = 'other';
        $info['field_content'] = 'table';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = '';
        $info['section_name'] = 'miscellaneous details';
        $info['section_misc_info'] = $miscChecklistStatus;
        $info['additional_field_name'] = "Exception";
        $info['additional_field_key'] = 'mandate_document_exception_remarks';
        $info['additional_field_display'] = 1;
        $info['additional_field_type'] = 'select';
        $info['additional_field_value'] = $exceptionRemarks;
        $info['field_misc'] = [];
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';
        $checklistData93 = $this->checklistStructure($info);
        unset($info);



        $data['isUserGeo'] = $this->getUserGeoLocationsDataV1($data['consumer_applications']);
        $gt[0] = $data['isUserGeo'];
        $e[0] = $this->generateCommonArray($gt,['distance','distance_type','is_negative_area']);
        $data['center_lat'] = '';
        $lats = [];
        $stops = [];
        foreach ($data['isUserGeo'] as $m_index => $location) {
            $lats[] = [
                'lat' => (float)$location['lat'],
                'lng' => (float)$location['lng'],
                'date' => $location['distance_type']
            ];
            if (!$data['center_lat']) {
                $data['center_lat'] = $location['lat'];
                $data['center_lng'] = $location['lng'];
            }
            if (isset($data['isUserGeo'][$m_index])) {
                $stops[] = ['origin' => ['lat' => $location['lat'], 'lng' => $location['lng']],
                    'destination' => ['lat' => $data['isUserGeo'][$m_index]['lat'], 'lng' => $data['isUserGeo'][$m_index]['lng']],
                    'distance' => $location['distance'], 'speed_mpm' => 0, 'date' => $location['distance_type']];
            }
        }
        $data['locations'] = $lats ?? '';
        $data['stops'] = $stops ?? '';

        $info['group_name'] = 'user geolocation';
        $info['customer_type'] = 'applicant';
        // $info['group_display'] = 0;
        // $info['application_data_display'] = 0;
        $info['name'] = 'user location';
        $info['key'] = 'user_location';
        $info['value'] = $e;
        $info['field_type'] = 'other';
        $info['field_content'] = 'table4';
        $info['field_required'] = 0;
        $info['field_display'] = 1;
        $info['field_value'] = '';
        $info['content_display'] = 1;
        $info['checklist_page'] = 'disbursement';

        $checklistData95 = $this->checklistStructure($info);
        unset($info);

        $info['group_name'] = 'user geolocation';
        $info['customer_type'] = 'applicant';
        // $info['group_display'] = 0;
        // $info['application_data_display'] = 0;
        $info['name'] = '';
        $info['key'] = '';
        $info['value'] = 'map';
        $info['field_type'] = 'other';
        $info['field_content'] = 'map';
        $info['field_required'] = 0;
        $info['field_display'] = 1; 
        $info['field_value'] = '';
        $info['content_display'] = 1;
        // $info['misc_content'] = ['distance','distance_type','is_negative_area'];
        $info['checklist_page'] = 'disbursement';

        $checklistData96 = $this->checklistStructure($info);
        unset($info);

        $data['checklistData'] = $this->concatenateArrays($checklistData9,$checklistData3,$checklistData80,$checklistData81,$checklistData82,$checklistData83,$checklistData84,$checklistData85,$checklistData10,$checklistData11,$checklistData,$checklistData69,$checklistData4,$checklistData8,$checklistData5,$checklistData1,$checklistData6,$checklistData7,$checklistData12,$checklistData13,$checklistData70,$checklistData71,$checklistData72,$checklistData73,$checklistData98,$checklistData97,$checklistData74,$checklistData75,$checklistData77,$checklistData78, $checklistData79,$checklistData15,$checklistData19,$checklistData234,$checklistData235,$checklistData107,$checklistData34,$checklistData20,$checklistData21,$checklistData152,$checklistData153,$checklistData164,$checklistData165,$checklistData154,$checklistData155,$checklistData52,$checklistData53,$checklistData64,$checklistData65,$checklistData54,$checklistData55,$checklistData56,$checklistData57,$checklistData58,$checklistData59,$checklistData60,$checklistData61,$checklistData35,$checklistData36,$checklistData37,$checklistData38,$checklistData48,$checklistData39,$checklistData31,$checklistData32,/*$checklistData33,*/$checklistData46,$checklistData40,$checklistData41,$checklistData47,$checklistData42,$checklistData43,$checklistData45, $checklistData90,$checklistData16,$checklistData17,$mandDocResult,$checklistData23,$checklistData91,$checklistData92,$checklistData93,$checklistData95,$checklistData96, $checklistData49, $checklistData50, $checklistData555, $checklistData301, $checklistData302, $checklistData305, $checklistData306, $checklistData307, $checklistData308, $checklistData309, $checklistData310, $checklistData311, $checklistData312, $checklistData313, $checklistData314, $checklistData315, $checklistData316, $checklistData317, $checklistData319, $checklistData320, $checklistData321, $checklistData322, $checklistData323, $checklistData324, $checklistData325, $checklistData326, $checklistData327, $checklistData328, $checklistData329, $checklistData330, $checklistData331, $checklistData332, $checklistData333, $checklistData334, $checklistData335, $checklistData336, $checklistData351, $checklistData352, $checklistData353, $checklistData354, $checklistData355, $checklistData356, $checklistData357, $checklistData358, $checklistData359, $checklistData360, $checklistData361, $checklistData362, $checklistData363, $checklistData364, $checklistData365, $checklistData366, $checklistData367, $checklistData368, $checklistData369, $checklistData370, $checklistData371, $checklistData372, $checklistData373, $checklistData374, $checklistData375);
        $data['get_multi_stage_properties'] = $this->getMultiStageProperties($id, $data['consumer_applications']->offer_id, []);

        return view('admin.consumer-application.checklist_page',$data);
    }


    public function concatenateArrays(...$arrays) {
        $result = array();
        foreach ($arrays as $array) {
            foreach ($array as $key => $value) {
                if (is_array($value)) {
                    // Recursively combine sub-arrays
                    if (isset($result[$key]) && is_array($result[$key])) {

                        $result[$key] = $this->concatenateArrays($result[$key], $value);
                    } else {

                        $result[$key] = $value;
                    }
                } elseif (array_key_exists($key, $result)) {
                    // Key already exists, concatenate the value
                    // if (!is_array($result[$key])) {
                    //     $result[$key] = array($result[$key]);
                    // }
                    if(!in_array($key, ['group_status','application_type_status','applicant','co-applicant','group_info'])){
                        $result[$key][] = $value;
                    }
                } else {
                    // Key doesn't exist, add it
                    if(!in_array($key, ['group_status','application_type_status','applicant','co-applicant','group_info'])){
                        $result[$key][] = $value;
                    }else{
                        $result[$key] = $value;
                    }

                }
            }
        }
        return $result;
    }

    public function generateTable4($data)
    {
        echo '<table class="table" style="table-layout: fixed;width: 100%;">';

        // Generate the table header dynamically based on the sub-array keys
        echo '<thead><tr>';
        foreach (current($data) as $subHeader => $subValue) {
            echo '<th class="font-weight-bold">' . ucwords(str_replace('_',' ',$subHeader)) . '</th>';
        }
        echo '</tr></thead>';

        foreach ($data as $header => $subData) {
            echo '<tr>';
            // echo '<td style="word-wrap: break-word">' . ucwords(str_replace('_',' ',$header)) . '</td>';
            foreach ($subData as $value) {
                echo '<td>' . (is_array($value) ? implode('<br>', $value) : $value) . '</td>';
            }
            echo '</tr>';
        }

        echo '</table>';
    }

    public function checkDocumentStatus($application_id, $documentType = null)
    {
        $application = ConsumerApplication::with('application_element','documents')
            ->where('id', $application_id)->first();
        if (!$application || !$application->application_element || !$application->documents || $documentType == null) {
            return '0';
        }
        return (new DisbursementController(new Request()))->getDocumentsStatus($application, $documentType, false);
    }

    public function generateTable2($data)
    {
        echo '<table class="table" style="table-layout: fixed;width: 100%;">';

        // Generate the table header dynamically based on the sub-array keys
        echo '<thead><tr><th></th>';
        foreach (current($data) as $subHeader => $subValue) {
            echo '<th class="font-weight-bold">' . ucwords(str_replace('_',' ',$subHeader)) . '</th>';
        }
        echo '</tr></thead>';

        foreach ($data as $header => $subData) {
            echo '<tr>';
            echo '<td style="word-wrap: break-word;" class="text-left">' . strtoupper(str_replace('_',' ',$header)) . '</td>';
            foreach ($subData as $value) {
                echo '<td style="word-wrap: break-word">' . (is_array($value) ? implode('<br>', $value) : $value) . '</td>';
            }
            echo '</tr>';
        }

        echo '</table>';
    }

    public function generateTable3($data)
    {
        echo '<table class="table">';

        // Generate the table header dynamically based on the array keys
        echo '<thead><tr>';
        foreach (array_keys($data) as $key) {
            echo '<th class="font-weight-bold">' . ucwords(str_replace('_', ' ', $key)) . '</th>';
        }
        echo '</tr></thead>';

        // Generate data rows
        foreach ($data as $row) {
            echo '<tr>';
            foreach ($row as $value) {
                echo '<td style="word-wrap: break-word;">' . (is_array($value) ? implode(' ', $value) : $value) . '</td>';
            }
            echo '</tr>';
        }

        echo '</table>';
    }

    public function generateCombinedTables($tables) {
        foreach ($tables as $table) {
            // Check if the table data and infoHeader are provided
            if(isset($table['data'])){
                $this->generateTable2($table['data']);
            }
        }
    }

    public function generateTable1($data,$infoHeader=[]) {
        if(count($data)){
            echo "<table class='table'>";
            echo "<thead><tr>";

            foreach ($data[0] as $key => $value) {
            //     // filter the keys
                $infoHeader = array_diff($infoHeader,[' ']);
                if(in_array($key,$infoHeader)){
                    if($key == 'user'){
                        echo "<th class='font-weight-bold'>Advisor</th>";
                    }else{
                        echo "<th class='font-weight-bold'>".ucwords(str_replace('_',' ',$key))."</th>";
                    }
                }
                $infoHeader = array_merge($infoHeader,[' ']);
            }

            echo "</tr></thead>";

            // Rows with values
            echo "<tbody>";
            foreach ($data as $row) {
                echo "<tr>";
                foreach ($row as $k => $value) {
                // filter the keys along with its value
                    if(in_array($k,$infoHeader)){
                        echo "<td>";
                        if (is_array($value)) {
                            // Recursive call for nested arrays
                            $this->generateTable1([$value],$infoHeader);
                        } else {
                            echo $value;
                        }
                    }
                    echo "</td>";
                }
                echo "</tr>";
            }
            echo "</tbody>";

            echo "</table>";
        }
    }

    public function generateCommonArray($data, $allowedKeys=[])
    {
        $commonArray = [];

        foreach ($data as $entry) {
            foreach ($entry as $key => $values) {
                foreach ($values as $subKey => $subValue) {
                    if (!empty($allowedKeys)){
                        // Check if the sub-key exists in the common array
                        if(in_array($subKey, $allowedKeys)) {
                            if (!isset($commonArray[$subKey])) {
                                // If not, initialize it as an empty array
                                $commonArray[$subKey] = [];
                            }
                            // Add the sub-value to the common array under the sub-key
                            $commonArray[$subKey][$key] = $subValue;
                        }
                    }else{
                        if (!isset($commonArray[$subKey])) {
                            // If not, initialize it as an empty array
                            $commonArray[$subKey] = [];
                        }
                        // Add the sub-value to the common array under the sub-key
                        $commonArray[$subKey][$key] = $subValue;
                    }
                }
            }
        }

        return $commonArray;
    }

    public function checkLenderEMIDay($lender, $date){
        $lenderDateMap = array('1' => array('05', '18'), '2' => array('05', '18'), '3' => array('07'), '4' => array('05'), '5' => array('05', '18'), '11' => array('05', '18'));
        $day = explode('-', $date);
        return (in_array(substr($day[2], 0, strrpos($day[2], ' ')), $lenderDateMap[$lender])) ? true : false;
    }

    public function checkLenderEMIDayV1($lender, $date){
        try{
            $lenderDateMap = array('1' => array('05', '18'), '2' => array('05', '18'), '3' => array('07'), '4' => array('05'), '5' => array('05', '18'), '11' => array('05', '18'));
            $day = explode('-', $date);
            $day2 = isset($day[2]) ? $day[2] : null;

            $result = [
                'day' => (int)substr($day2, 0, strrpos($day2, ' ')),
                'status' =>  (in_array(substr($day2, 0, strrpos($day2, ' ')), $lenderDateMap[$lender])) ? true : false
            ];
            return $result;
    }catch (\Exception $e){
        //return \response()->json(['status' => 'failed','error' => $e->getMessage().' '.$e->getFile().' '.$e->getLine()], 200);
        (new Slack(new Request(['title' => 'Check Lender EMI Day', 'fields' => ['error'=>$e->getMessage(),'line'=>$e->getLine(),'trace'=>$e->getTraceAsString()]])))->send();
    }
    }

   
    public function verifyDocument(Request $request)
    {
        $status = 'FAIL';
        $message = 'Failed to verify document';

        $application_id = $request->get('id');
        $action = $request->get('action');
        $document_type = $request->get('file_type');
        $applicant_type = $request->get('applicant_type');

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

        $application = $this->getLatestFile($application_id, $document_type, $applicant_type);

        if (!isset($application->documents[0]->id)) {
            return response()->json(['status' => $status, 'message' => 'Document not found!']);
        }

        if ($action === 'accept') {
            $this->setFileAccepted($application_id, $application);
        } else {
            $this->setFileRejected($application);
        }

        $status = 'OK';
        $message = 'Document ' . ($action === 'accept' ? 'accepted' : 'rejected') . ' successfully!';

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

    private function checkEligibilityForDocumentVerification($consumer_application)
    {
        if($consumer_application->merchant_id == _env('SSE_MERCHANT_ID') ){
            return true;
        }
        return false;
    }

    private function getLatestFile($application_id, $document_type = null, $applicant_type = null)
    {
        if(isset($document_type)){
            return ConsumerApplication::with(['documents' => function ($query) use ($document_type, $applicant_type) {
                    $query->where('file_type', $document_type)
                        ->whereNull('deleted_at')
                        ->latest()     // order by created_at or id desc
                        ->limit(1);    // only latest
                }])
                ->where('id', $application_id)
                ->first();
        }
        return;
    }

    private function setFileAccepted($application_id, $application)
    {
        $application->documents[0]->doc_verify = 1;
        $application->documents[0]->save();
        if ($application->documents[0]->file_type == 'advance_amount_receipt') {
            $this->updateApplicationElement($application_id);
        }
        $this->webhook($application_id, ['type' => 'Document-Verification-Webhook', 'status' => 'approved', 'data' => ['applicantType' => $application->documents[0]->applicant_type, 'documentType' => $application->documents[0]->file_type, 'reason' => '']]);

        // If it's a self-attested file checking if all self-attested docs are verified
        if ($this->isSelfAttested($application->documents[0]->file_type)) {
            if ($this->checkSelfAttestedVerified($application_id, $application->documents[0]->applicant_type)) {
                // All self-attested docs accepted fire KYC accepted
                $this->webhook($application_id, ['type' => 'VKYC-Webhook','status' => 'approved', 'data' => ['vendor'=> 'self-attested', 'applicantType' => $application->documents[0]->applicant_type]]);
                $tag = (new LoanHypothecation(new Request()))->getSSEAdvisorsTag();
                $commentText = $tag . " Self-attested KYC document is approved. Please proceed with OSV";
                $markComment = (new GradeController(new Request()))->addComment($application_id, Auth::user()->id ?? 107, $commentText);
                $sendDAWebhook = (new WebhookController())->pushDAWebhook($application_id, 'vkyc');
                if ($sendDAWebhook) {
                    $this->webhook($application_id, ['type' => 'DA-Confirmation-Webhook','status' => 'pending', 'data' => $this->getMConnectPayload($application_id, 'DA-Confirmation-Webhook')]);
                }
            }
        }
    }

    private function updateApplicationElement($application_id)
    {
        $applicationElement = ConsumerApplicationElement::where('application_id', $application_id)->first();
        if ($applicationElement) {
            $applicationElement->advance_payment_verified = 1;
            $applicationElement->save();
        }
    }

    private function setFileRejected($application)
    {
        $application->documents[0]->doc_verify = 0;
        $application->documents[0]->save();
        $this->webhook($application->id, ['type' => 'Document-Verification-Webhook', 'status' => 'rejected', 'data' => ['applicantType' => $application->documents[0]->applicant_type, 'documentType' => $application->documents[0]->file_type, 'reason' => '']]);
        $username = isset(Auth::user()->name) ? Auth::user()->name : 'creditfair';
        $commentText = "KYC Rejected. The Document ". $application->documents[0]->file_type. " has been rejected by ". $username;
        $markComment = (new GradeController(new Request()))->addComment($application->id, Auth::user()->id ?? 107, $commentText);

        // If it's a self-attested file rejecting KYC too
        if ($this->isSelfAttested($application->documents[0]->file_type)) {
            $this->webhook($application->id, ['type' => 'VKYC-Webhook','status' => 'rejected', 'data' => ['vendor'=> 'self-attested', 'applicantType' => $application->documents[0]->applicant_type]]);
        }
    }

    private function isSelfAttested($file_type)
    {
        $selfAttestedTypes = [
            'self_attested_pan',
            'self_attested_aadhar',
            'self_attested_co_pan',
            'self_attested_co_aadhar',
            'self_attested_selfie',
            'self_attested_co_selfie',
            'customer_photo',
            'co_applicant_customer_photo'
        ];

        return in_array($file_type, $selfAttestedTypes);
    }

    private function checkSelfAttestedVerified($application_id, $applicant_type = null)
    {
        $doc_list = $applicant_type == '1'
            ? ['self_attested_pan', 'self_attested_aadhar']
            : ['self_attested_co_pan', 'self_attested_co_aadhar'];

        $selfieDocList = $applicant_type == '1'
            ? ['self_attested_selfie', 'customer_photo']
            : ['self_attested_co_selfie', 'co_applicant_customer_photo'];

        $live_photo = DB::select("select id, doc_verify from consumer_application_files where consumer_application_id = ? and applicant_type = ? and deleted_at is null and ((file_type = ? and doc_verify = 1) or (file_type = ? and doc_verify = 1)) order by created_at desc limit 1", [$application_id, $applicant_type, $selfieDocList[0], $selfieDocList[1]]);

        $attestedDocs = ConsumerApplicationFiles::where('consumer_application_id', $application_id)
            ->whereIn('file_type', $doc_list)
            ->where('doc_verify', 1)
            ->where('applicant_type', $applicant_type)
            ->whereNull('deleted_at')
            ->count() === count($doc_list);
        return (isset($live_photo) && count($live_photo) > 0 && $attestedDocs);
    }

    public function checkDocsUploaded($applicationId)
    {
        $application = ConsumerApplication::with('documents')->find($applicationId);
            $has_co_pan = $application && $application->documents->where('file_type', 'self_attested_co_pan')->count() > 0;
            $has_co_aadhar = $application && $application->documents->where('file_type', 'self_attested_co_aadhar')->count() > 0;
            $has_co_selfie = $application && $application->documents->where('file_type', 'self_attested_co_selfie')->count() > 0;
            if (!$has_co_selfie) {
                $has_co_selfie = $application && $application->documents->where('file_type', 'co_applicant_customer_photo')->count() > 0;
            }
            
            $has_pan = $application && $application->documents->where('file_type', 'self_attested_pan')->count() > 0;
            $has_aadhar = $application && $application->documents->where('file_type', 'self_attested_aadhar')->count() > 0;
            $has_selfie = $application && $application->documents->where('file_type', 'self_attested_selfie')->count() > 0;
            if (!$has_selfie) {
                $has_selfie = $application && $application->documents->where('file_type', 'customer_photo')->count() > 0;
            }
        
         $all_uploaded_applicant = $has_pan && $has_aadhar && $has_selfie;

         $all_uploaded_coapplicant = $has_co_pan && $has_co_aadhar && $has_co_selfie;

        return response()->json([
            'all_uploaded_applicant' => $all_uploaded_applicant,
            'all_uploaded_coapplicant' => $all_uploaded_coapplicant
        ]);
    }

    public function addNewBank(Request $request){

        $message = 'Failed to add '.trim($request->get('bank'));
        $status = 'FAIL';
        if($request->get('id')){

            $nachSupportedBank = NachSupportedBank::where('bank', trim($request->get('bank')))->first(['id']);
            if(isset($nachSupportedBank->id)){
                $message = trim($request->get('bank')).' already added!';
            }else {

                NachSupportedBank::insert([
                    'bank_code' => $request->get('bank_code'),
                    'bank' => trim($request->get('bank')),
                    'type_of_bank' => '',
                    'ifsc' => '',
                    'micr' => '',
                    'iin' => '',
                    'created_at' => Carbon::now()->toDateTimeString()
                ]);

                $status = 'OK';
                $message = trim($request->get('bank')).' added successfully!';
            }
        }

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

    public function initChecklist($application_id){
        $consumerApplication = ConsumerApplication::with('calls')->where('id', $application_id)->first(['id','name','created_by','state']);
        $this->fetchCallDetails($consumerApplication, new Request());
        return response()->json(['status' => 'OK'], 200);
    }

    public function getAddressMappedDocumentV1($application){
        $items = ['permanent_address','current_address'];
        $lists = [];
        foreach ($items as $item){
            if($application->Checklist) {
                $document_path = '';
                $id = $item == 'current_address' ? $application->Checklist->current_address_document : $application->Checklist->permanent_address_document;
                if($id) {
                    $document = ConsumerApplicationFiles::where('id', $id)->first(['file_path']);
                    if (isset($document->file_path)) {
                        $document_path = $document->file_path;
                    }
                }
            }

            $lists[$item] = isset($document_path) && $document_path ? $document_path : '';
        }

        return $lists;
    }

    public function getAddressMappedDocument($application){
        $items = ['permanent_address','current_address'];
        $lists = [];
        foreach ($items as $item){
            if($application->Checklist) {
                $document_path = '';
                $id = $item == 'current_address' ? $application->Checklist->current_address_document : $application->Checklist->permanent_address_document;
                if($id) {
                    $document = ConsumerApplicationFiles::where('id', $id)->first(['file_path']);
                    if (isset($document->file_path)) {
                        $document_path = $document->file_path;
                    }
                }
            }

            $lists[$item] = isset($document_path) && $document_path ? $document_path : '';
        }

        return $lists;
    }

    public function getKYCInfo($application)
    {
        $data = [];
        $coAppPan = [];
        $coAppAadhar = [];
        $appPan = [];
        $appPan_osv = [];
        $appAadhar_front_osv = [];
        $appAadhar_front = [];
        $appAadhar_back_osv = [];
        $appAadhar_back = [];
        $selfie = [];
        $pan = 0;
        $pan_osv = 0;
        $aadhar_front_osv = 0;
        $aadhar_front = 0;
        $aadhar_back_osv = 0;
        $aadhar_back = 0;
        $app_selfie = 0 ;
        if ($application->documents) {
            $documents = ($application->documents)->reverse();
            foreach ($documents as $document) {
                if ($document->file_type == 'customer_cam_image') {
                    $data['esign'][] = $document->file_path;
                } else if (strpos($document->file_type, 'cpv') !== false) {
                    $data['cpv'][] = $document->file_path;
                } else if (strpos($document->file_type, 'co_applicant_pan_card') !== false) {
                    $coAppPan[] = $document->file_path;
                    //$data['Co_Applicant_Pan_card'][] = $document->file_path;
                } else if ($document->file_type == 'pan_card_masked') {
                    if($pan_osv == 1){
                        continue;
                    }
                    $appPan_osv[] = $document->file_path;
                    $pan_osv = 1;
                } else if ($document->file_type == 'pan_card') {
                    if($pan == 1){
                        continue;
                    }
                    $appPan[] = $document->file_path;
                    $pan = 1;
                } else if (strpos($document->file_type, 'co_applicant_aadhar_card') !== false) {
                    $coAppAadhar[] = $document->file_path;
                    //$data['Co_Applicant_aadhar_card'][] = $document->file_path;
                } else if ($document->file_type == 'aadhar_card_masked') {
                    if($aadhar_front_osv == 1){
                        continue;
                    }
                    //$data['Applicant_aadhar_card'][] = $document->file_path;
                    $appAadhar_front_osv[] = $document->file_path;
                    $aadhar_front_osv = 1;
                } else if ($document->file_type == 'aadhar_card_back_masked') {
                    if($aadhar_back_osv == 1){
                        continue;
                    }
                    $appAadhar_back_osv[] = $document->file_path;
                    $aadhar_back_osv = 1;
                } else if ($document->file_type == 'aadhar_card') {
                    if($aadhar_front == 1){
                        continue;
                    }
                    //$data['Applicant_aadhar_card'][] = $document->file_path;
                    $appAadhar_front[] = $document->file_path;
                    $aadhar_front = 1;
                } else if ($document->file_type == 'aadhar_card_back') {
                    if($aadhar_back == 1){
                        continue;
                    }
                    $appAadhar_back[] = $document->file_path;
                    $aadhar_back = 1;
                } else if (strpos($document->file_type,'customer_photo') !== false) {
                    if($app_selfie == 1){
                        continue;
                    }
                    $selfie[] = $document->file_path;
                    $app_selfie = 1;
                } else if (strpos($document->file_type, 'CUSTPHOTO_'.$application->id.'_1') !== false) {
                    if($app_selfie == 1){
                        continue;
                    }
                    $selfie[] = $document->file_path;
                    $app_selfie = 1;
                }
            }


            if($appPan_osv){
                foreach($appPan_osv as $item){
                    $data['Applicant_Pan_card'][] = $item;
                }
            }elseif($appPan){
                foreach($appPan as $item){
                    $data['Applicant_Pan_card'][] = $item;
                }
            }
            if($appAadhar_front_osv){
                foreach($appAadhar_front_osv as $item){
                    $data['Applicant_aadhar_card_front'][] = $item;
                }
            }elseif($appAadhar_front){
                foreach($appAadhar_front as $item){
                    $data['Applicant_aadhar_card_front'][] = $item;
                }
            }
            if($appAadhar_back_osv){
                foreach($appAadhar_back_osv as $item){
                    $data['Applicant_aadhar_card_back'][] = $item;
                }
            }elseif($appAadhar_back){
                foreach($appAadhar_back as $item){
                    $data['Applicant_aadhar_card_back'][] = $item;
                }
            }
            if($coAppPan){
                foreach($coAppPan as $item){
                    $data['Co_Applicant_Pan_card'][] = $item;
                }
            }
            if($coAppAadhar){
                foreach($coAppAadhar as $item){
                    $data['Co_Applicant_aadhar_card'][] = $item;
                }
            }
            if($selfie){
                foreach($selfie as $item){
                    $data['Applicant_Selfie'][] = $item;
                }
            }
        }
        if($app_selfie == 0) {
            $data['Applicant_Selfie'][] = ['missing' => "Customer Selfie is missing"];
        }
        if (!isset($data['esign'])) {
            $data['esign'][] = ['missing' => 'E-Sign Customer Photo is Missing'];
        }

        return $data;
    }

    public function getPincodeData($data, $isData = false)
    {
        if (!$data['pincode']) {
            $apiData = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?latlng=' . $data['latitude'] . ',' . $data['longitude'] . '&key=AIzaSyBJ5sOPcuh4edXH5KgE3vKqeZCfyO9JlHY');
            $apiData = json_decode($apiData);
            if ($apiData->status == "OK") {
                if($isData){
                    return $apiData;
                }
                if (isset($apiData->results)) {
                    foreach ($apiData->results as $result) {
                        if ($result->address_components) {
                            foreach ($result->address_components as $address_component) {
                                if(isset($data['type']) && $data['type'] == 'state'){
                                    if (isset($address_component->types) && isset($address_component->types[0]) && $address_component->types[0] == 'administrative_area_level_1') {
                                        if(isset($address_component->long_name)){
                                            return $address_component->long_name;
                                        }
                                    }
                                }else{
                                    if (isset($address_component->types) && isset($address_component->types[0]) && $address_component->types[0] == 'postal_code') {
                                        if (strlen($address_component->long_name) == 6) {
                                            return $address_component->long_name;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }


    public function initGeoData($application)
    {
        $userGeolocation = UserGeolocation::where('_id', $application->id)->where('applicant_type', 1)->where('id_type', 'application_id')->whereNull('deleted_at')->get();

        foreach ($userGeolocation as $geoItem) {
            if (!$geoItem->pincode) {
                $pincode = $this->getPincodeData(['pincode' => $geoItem->pincode, 'latitude' => $geoItem->latitude, 'longitude' => $geoItem->longitude]);
                if ($pincode) {
                    UserGeolocation::where('id', $geoItem->id)->update(['pincode' => $pincode]);
                }
            }
        }
    }

    public function sendFinbitLink($id)
    {
        try {
            if ($id) {
                $link = URL::to('/').'/netbanking/authentication/' . $id;
                $application = ConsumerApplication::where('id', $id)->first(['id', 'name', 'email','mobile_number']);
                $messageOutput = '';
                if ($application->email) {
                    $button = '<table style="width: 100%;text-align: center;"><tr><td><span style="display: inline-block; border-radius: 4px; background-color: rgb(46, 166, 100);">
				<a href="' . $link . '" style="min-width: 196px; border-width: 13px 24px; border-style: solid; border-color: rgb(67, 217, 231); border-image: initial; border-radius: 4px; background-color: rgb(67, 217, 231); color: rgb(255, 255, 255); font-size: 16px; line-height: 18px; word-break: break-word; display: inline-block; text-align: center; font-weight: 900; text-decoration: none;" target="_blank">Authenticate With NetBanking</a></span></td></tr></table>';
                    $body = "Dear " . $application->name . ",<br/>Thanks for your loan application and sharing your details with us.<br/> To ensure a quick turnaround, we would  request you to provide us with your latest bank statement by clicking on the link given below.<br/><br/> " . $button . "<br/><br/> You will be required to login using your netbanking credentials.<br/>Feel free to reach out to us at 9967235047 for any queries.<br/>";

                    Mail::send('emails.reminders.basic_reminder',
                        ['body' => $body]
                        , function ($message) use ($application) {
                            $message->to($application->email)->subject('Upload Latest Bank Statement using Netbanking');
                        });

                    $messageOutput = "Email sent successfully";
                }

                if ($application->mobile_number) {
                    try {
                        $url = Shortio::getUrl($link);
                    }catch (\Exception $e){
                        $url = $link;
                    }
                    $message = "Dear " . $application->name . ",<br>Thank you for applying with Credit Fair. Please login using your net banking credentials on this link " . $url . " to submit your latest bank statement.,<br/>Regards,<br/>Team Credit Fair";
                    $entity = ['templateid' => '1307159973997709435', 'entityid' => Templates::$entityid];
                    send_sms($application->mobile_number, ['message'=>$message,'id'=>$application->id,'id_type'=>'application_id','templateId' => Templates::$net_banking_statement_c2, 'args' => [$application->name, $url], 'templateDetails' => $entity]);
                    $messageOutput = $messageOutput ? "Email & Message sent successfully" : "Message sent successfully";
                }

                if ($messageOutput) {
                    \Session::flash('success', $messageOutput);
                } else {
                    \Session::flash('error', 'Application don\'t have contact details');
                }
                return \redirect()->back();
            }
        } catch (\Exception $e) {
            \Session::flash('error', 'Something went wrong, Please try again later');
            return \redirect()->back();
        }
    }

    public function getUserGeoLocationsData($application)
    {
        $this->initGeoData($application);

        $userGeolocation = UserGeolocation::where('_id', $application->id)->where('applicant_type', 1)->where('id_type', 'application_id')->whereNull('deleted_at')->get();

        $readyServices = [];
        $readyServicesInfo = [];
        foreach ($userGeolocation as $geoItem) {
            $readyServices[$geoItem->applicant_type][] = $geoItem->service;
            $readyServicesInfo[$geoItem->applicant_type][$geoItem->service] = $geoItem;

        }

        $data = [];
        $response = [];
        $geoData = [];
        $addressees = $this->getAddressByType($application);
        foreach ($addressees as $applicant_type => $address) {
            foreach ($address as $address_type => $item) {
                if(isset($item['pincode']) && !empty($item['pincode']) && strlen($item['address']) > 5){

                    $_applicant_type_int = $applicant_type == 'applicant' ? 1 : 2;

                    $isProcessed = isset($readyServices[$_applicant_type_int]) && in_array($address_type, $readyServices[$_applicant_type_int]) ? false : true;


                    if ($item['address'] && $isProcessed) {
                        $geoLatLng = $this->getGeocodingDataFromAddress($item);
                        if ($geoLatLng) {
                            $data[$applicant_type][$address_type] = $geoLatLng;
                            $geoData[] = ['lat' => $geoLatLng['lat'], 'lng' => $geoLatLng['lng'], 'pincode' => $geoLatLng['pincode'], 'applicant_type' => $applicant_type, 'address_type' => $address_type];
                        }
                    } else {
                        if (isset($readyServicesInfo[$_applicant_type_int][$address_type])) {
                            $geoDataInfo = $readyServicesInfo[$_applicant_type_int][$address_type];
                            $__applicant_type_int = $geoDataInfo->applicant_type == 1 ? 'applicant' : 'co_applicant';
                            $data[$applicant_type][$address_type] = ['lat' => $geoDataInfo->latitude, 'lng' => $geoDataInfo->longitude, 'pincode' => $geoDataInfo->pincode];
                            $geoData[] = ['lat' => $geoDataInfo->latitude, 'lng' => $geoDataInfo->longitude, 'pincode' => $geoDataInfo->pincode, 'applicant_type' => $__applicant_type_int, 'address_type' => $address_type];
                        }
                    }
                }
            }
        }

        foreach ($geoData as $item) {
            $applicant_id = $item['applicant_type'] == 'co_applicant' ? $application->co_applicant_id : $application->applicant_id;
            $this->saveUserGeolocation($application, ['applicant_type' => ($item['applicant_type'] == 'applicant' ? 1 : 2), 'applicant_id' => $applicant_id, 'id_type' => 'application_id', 'service' => $item['address_type'], 'longitude' => $item['lng'], 'latitude' => $item['lat'], 'pincode' => $item['pincode']]);
        }

        foreach ($userGeolocation as $key => $item) {
            if (in_array($item->service, ['cpv', 'esign'])) {
                foreach ($data as $_applicant_type => $_addressGeo) {
                    foreach ($_addressGeo as $_address_type => $addressGeo) {
                        $km = $this->getDistanceDetail(['lat' => $item->latitude, 'lng' => $item->longitude], ['lat' => $addressGeo['lat'], 'lng' => $addressGeo['lng']]);
                        if (!is_nan($km)) {
                            $response[$item->service][$_applicant_type][$_address_type] = ['distance' => $km, 'lat' => $addressGeo['lat'], 'lng' => $addressGeo['lng'], 'pincode' => $addressGeo['pincode'], 'service' => ucfirst($_address_type)];
                        }
                    }
                }
                $response[$item->service][$item->service] = ['distance' => 0, 'lat' => $item->latitude, 'lng' => $item->longitude, 'pincode' => $item->pincode, 'service' => ucfirst($item->service)];
            }
        }

        $responseData = [];
        foreach ($response as $key_name => $mainItem) {
            if (isset($mainItem[$key_name])) {

                $next_name = $key_name == 'cpv' ? 'esign' : $key_name;

                if (isset($response[$next_name][$next_name]) && isset($response[$next_name][$next_name]['lat']) && isset($response[$next_name][$next_name]['lng'])) {
                    $km = $this->getDistanceDetail(['lat' => $mainItem[$key_name]['lat'], 'lng' => $mainItem[$key_name]['lng']], ['lat' => $response[$next_name][$next_name]['lat'], 'lng' => $response[$next_name][$next_name]['lng']]);
                    if (!is_nan($km)) {
                        $response[$key_name][$key_name]['distance'] = $km;
                        $response[$key_name][$key_name]['distance_type'] = 'Distance From ' . ucfirst($key_name) . ' To ' . ucfirst($next_name);
                        $response[$key_name][$key_name]['distance_type_first'] = ucfirst($key_name);

                        if (isset($response[$key_name][$key_name]['pincode'])) {
                            $response[$key_name][$key_name]['is_negative_area'] = NegativeArea::where('pincode', $response[$key_name][$key_name]['pincode'])->first(['level']);
                        }

                        $responseData[] = $response[$key_name][$key_name];
                    }
                }


                $next_name = $key_name == 'esign' ? 'cpv' : $key_name;

                if (isset($response[$next_name][$next_name]) && isset($response[$next_name][$next_name]['lat']) && isset($response[$next_name][$next_name]['lng'])) {
                    $km = $this->getDistanceDetail(['lat' => $mainItem[$key_name]['lat'], 'lng' => $mainItem[$key_name]['lng']], ['lat' => $response[$next_name][$next_name]['lat'], 'lng' => $response[$next_name][$next_name]['lng']]);
                    if (!is_nan($km)) {
                        $response[$key_name][$key_name]['distance'] = $km;
                        $response[$key_name][$key_name]['distance_type'] = 'Distance From ' . ucfirst($key_name) . ' To ' . ucfirst($next_name);
                        $response[$key_name][$key_name]['distance_type_first'] = ucfirst($key_name);

                        if (isset($response[$key_name][$key_name]['pincode'])) {
                            $response[$key_name][$key_name]['is_negative_area'] = NegativeArea::where('pincode', $response[$key_name][$key_name]['pincode'])->first(['level']);
                        }

                        $responseData[] = $response[$key_name][$key_name];
                    }
                }


                if (isset($mainItem['applicant'])) {
                    foreach ($mainItem['applicant'] as $to_key => $itemData) {
                        $itemData['distance_type'] = 'Distance From ' . ucfirst($key_name) . ' To ' . ucfirst($to_key) . ' Address';
                        $itemData['distance_type_first'] = ucfirst($key_name);

                        if (isset($itemData['pincode'])) {
                            $itemData['is_negative_area'] = NegativeArea::where('pincode', $itemData['pincode'])->first(['level']);
                        }

                        $responseData[] = $itemData;
                    }
                }
            }
        }

        usort($responseData, function ($a, $b) {
            return $a['distance'] <=> $b['distance'];
        });
        return $responseData;
    }

    public function getUserGeoLocationsDataV1($application)
    {
        $this->initGeoData($application);

        $userGeolocation = UserGeolocation::where('_id', $application->id)->where('applicant_type', 1)->where('id_type', 'application_id')->whereNull('deleted_at')->get();

        $readyServices = [];
        $readyServicesInfo = [];
        foreach ($userGeolocation as $geoItem) {
            $readyServices[$geoItem->applicant_type][] = $geoItem->service;
            $readyServicesInfo[$geoItem->applicant_type][$geoItem->service] = $geoItem;

        }

        $data = [];
        $response = [];
        $geoData = [];
        $addressees = $this->getAddressByType($application);
        foreach ($addressees as $applicant_type => $address) {
            foreach ($address as $address_type => $item) {
                if(isset($item['pincode']) && !empty($item['pincode']) && strlen($item['address']) > 5){

                    $_applicant_type_int = $applicant_type == 'applicant' ? 1 : 2;

                    $isProcessed = isset($readyServices[$_applicant_type_int]) && in_array($address_type, $readyServices[$_applicant_type_int]) ? false : true;


                    if ($item['address'] && $isProcessed) {
                        $geoLatLng = $this->getGeocodingDataFromAddress($item);
                        if ($geoLatLng) {
                            $data[$applicant_type][$address_type] = $geoLatLng;
                            $geoData[] = ['lat' => $geoLatLng['lat'], 'lng' => $geoLatLng['lng'], 'pincode' => $geoLatLng['pincode'], 'applicant_type' => $applicant_type, 'address_type' => $address_type];
                        }
                    } else {
                        if (isset($readyServicesInfo[$_applicant_type_int][$address_type])) {
                            $geoDataInfo = $readyServicesInfo[$_applicant_type_int][$address_type];
                            $__applicant_type_int = $geoDataInfo->applicant_type == 1 ? 'applicant' : 'co_applicant';
                            $data[$applicant_type][$address_type] = ['lat' => $geoDataInfo->latitude, 'lng' => $geoDataInfo->longitude, 'pincode' => $geoDataInfo->pincode];
                            $geoData[] = ['lat' => $geoDataInfo->latitude, 'lng' => $geoDataInfo->longitude, 'pincode' => $geoDataInfo->pincode, 'applicant_type' => $__applicant_type_int, 'address_type' => $address_type];
                        }
                    }
                }
            }
        }

        foreach ($geoData as $item) {
            $applicant_id = $item['applicant_type'] == 'co_applicant' ? $application->co_applicant_id : $application->applicant_id;
            $this->saveUserGeolocation($application, ['applicant_type' => ($item['applicant_type'] == 'applicant' ? 1 : 2), 'applicant_id' => $applicant_id, 'id_type' => 'application_id', 'service' => $item['address_type'], 'longitude' => $item['lng'], 'latitude' => $item['lat'], 'pincode' => $item['pincode']]);
        }

        foreach ($userGeolocation as $key => $item) {
            if (in_array($item->service, ['cpv', 'esign'])) {
                foreach ($data as $_applicant_type => $_addressGeo) {
                    foreach ($_addressGeo as $_address_type => $addressGeo) {
                        $km = $this->getDistanceDetail(['lat' => $item->latitude, 'lng' => $item->longitude], ['lat' => $addressGeo['lat'], 'lng' => $addressGeo['lng']]);
                        if (!is_nan($km)) {
                            $response[$item->service][$_applicant_type][$_address_type] = ['distance' => $km, 'lat' => $addressGeo['lat'], 'lng' => $addressGeo['lng'], 'pincode' => $addressGeo['pincode'], 'service' => ucfirst($_address_type)];
                        }
                    }
                }
                $response[$item->service][$item->service] = ['distance_type'=> '','is_negative_area'=>'','distance' => 0, 'lat' => $item->latitude, 'lng' => $item->longitude, 'pincode' => $item->pincode, 'service' => ucfirst($item->service)];
            }
        }

        $responseData = [];
        foreach ($response as $key_name => $mainItem) {
            if (isset($mainItem[$key_name])) {

                $next_name = $key_name == 'cpv' ? 'esign' : $key_name;

                if (isset($response[$next_name][$next_name]) && isset($response[$next_name][$next_name]['lat']) && isset($response[$next_name][$next_name]['lng'])) {
                    $km = $this->getDistanceDetail(['lat' => $mainItem[$key_name]['lat'], 'lng' => $mainItem[$key_name]['lng']], ['lat' => $response[$next_name][$next_name]['lat'], 'lng' => $response[$next_name][$next_name]['lng']]);
                    if (!is_nan($km)) {
                        $response[$key_name][$key_name]['distance'] = $km;
                        $response[$key_name][$key_name]['distance_type'] = 'Distance From ' . ucfirst($key_name) . ' To ' . ucfirst($next_name);
                        $response[$key_name][$key_name]['distance_type_first'] = ucfirst($key_name);

                        if (isset($response[$key_name][$key_name]['pincode'])) {
                            $n = NegativeArea::where('pincode', $response[$key_name][$key_name]['pincode'])->first(['level']);
                            $response[$key_name][$key_name]['is_negative_area'] = isset($n->level) ? strtoupper($next_name).' Address is in Negative Area' : '';
                        }

                        $responseData[] = $response[$key_name][$key_name];
                    }
                }


                $next_name = $key_name == 'esign' ? 'cpv' : $key_name;

                if (isset($response[$next_name][$next_name]) && isset($response[$next_name][$next_name]['lat']) && isset($response[$next_name][$next_name]['lng'])) {
                    $km = $this->getDistanceDetail(['lat' => $mainItem[$key_name]['lat'], 'lng' => $mainItem[$key_name]['lng']], ['lat' => $response[$next_name][$next_name]['lat'], 'lng' => $response[$next_name][$next_name]['lng']]);
                    if (!is_nan($km)) {
                        $response[$key_name][$key_name]['distance'] = $km;
                        $response[$key_name][$key_name]['distance_type'] = 'Distance From ' . ucfirst($key_name) . ' To ' . ucfirst($next_name);
                        $response[$key_name][$key_name]['distance_type_first'] = ucfirst($key_name);

                        if (isset($response[$key_name][$key_name]['pincode'])) {
                            $n = NegativeArea::where('pincode', $response[$key_name][$key_name]['pincode'])->first(['level']);
                            $response[$key_name][$key_name]['is_negative_area'] = isset($n->level) ? strtoupper($next_name).' Address is in Negative Area' : '';
                        }

                        $responseData[] = $response[$key_name][$key_name];
                    }
                }


                if (isset($mainItem['applicant'])) {
                    foreach ($mainItem['applicant'] as $to_key => $itemData) {
                        $itemData['distance_type'] = 'Distance From ' . ucfirst($key_name) . ' To ' . ucfirst($to_key) . ' Address';
                        $itemData['distance_type_first'] = ucfirst($key_name);

                        if (isset($itemData['pincode'])) {
                            $itemData['is_negative_area'] = NegativeArea::where('pincode', $itemData['pincode'])->first(['level']);
                        }

                        $responseData[] = $itemData;
                    }
                }
            }
        }

        usort($responseData, function ($a, $b) {
            return $a['distance'] <=> $b['distance'];
        });
        return $responseData;
    }

    public function getSignDocumentsV1($application)
    {
        $data = [];
        if ($application->documents) {
            foreach ($application->documents as $document) {
                if (strpos($document->file_type, 'pan_card') !== false) {
                    $data['pan_card'][] = $document->file_path;
                } else if (strpos($document->file_type, 'nach') !== false) {
                    $data['nach'][] = $document->file_path;
                } else if (strpos($document->file_type, 'cheque') !== false) {
                    $data['cheque'][] = $document->file_path;
                } else if (strpos($document->file_type, 'self_attested') !== false) {
                    $data['self_attested'][] = $document->file_path;
                }
            }
        }

        return $data;
    }

    public function getSignDocuments($application)
    {
        $data = [];
        if ($application->documents) {
            foreach ($application->documents as $document) {
                if (strpos($document->file_type, 'pan_card') !== false) {
                    $data['pan_card'][] = $document->file_path;
                } else if (strpos($document->file_type, 'nach') !== false) {
                    $data['nach'][] = $document->file_path;
                } else if (strpos($document->file_type, 'cheque') !== false) {
                    $data['cheque'][] = $document->file_path;
                } else if (strpos($document->file_type, 'self_attested') !== false) {
                    $data['self_attested'][] = $document->file_path;
                }
            }
        }

        return $data;
    }

    public function getDisbursementData($application_id)
    {

        $data = [];
        try {
            $application = ConsumerApplication::with('documents', 'merchant', 'emi')->where('id', $application_id)->first();

            $documents = ['aadhar_card', 'electricity_bill', 'gas_bill', 'utilitybillvalidation', 'passport'];
            $nameOfDocument = [];
            if ($application->documents) {
                foreach ($application->documents as $document_name) {
                    foreach ($documents as $item) {
                        if ($document_name->file_type == $item) {
                            if(strpos($document_name->file_path, 'res.cloudinary.com/') == true){
                                $nameOfDocument[ucwords(str_replace('_', ' ', $item))] =  $document_name->file_path;
                            }else{
                                $nameOfDocument[ucwords(str_replace('_', ' ', $item))] = '/admin/consumer-application/get-documents/' . $document_name->file_path;
                            }
                        }

                    }
                }
            }

            $data = [
                'name' => $application->name,
                'address' => [
                    'permanent' => $application->permanent_address_line_1 . ' ' . $application->permanent_address_state . ' ' . $application->permanent_address_city . ' ' . $application->permanent_address_landmark . ' ' . $application->permanent_address_pincode,
                    'current' => $application->current_address_line_1 . ' ' . $application->current_address_state . ' ' . $application->current_address_city . ' ' . $application->current_address_landmark . ' ' . $application->current_address_pincode,
                ],
                'merchant_name' => isset($application->merchant->merchant_name) ? $application->merchant->merchant_name : '',
                'approved_amount' => $application->approved_amount,
                'co_applicant' => [
                    'name' => $application->co_applicant_name,
                    'address' => $application->co_applicant_address_line_1 . ' ' . $application->co_applicant_address_state . ' ' . $application->co_applicant_address_city . ' ' . $application->co_applicant_address_landmark . ' ' . $application->co_applicant_address_pincode,
                ],
                'tenure' => ($application->emi) ? $application->emi->tenure . ' Months' : '<span style="color: red;">* No EMI</span>',
                'interest_rate' => ($application->emi) ? $application->emi->interest_rate . '%' : '<span style="color: red;">* No EMI</span>',
                'document' => $nameOfDocument
            ];
            $status = 'OK';
        } catch (\Exception $exception) {
            $status = 'FAIL';
        }

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

    }

    public function AcceptableData($key, $value, $application, $data = array()){
        switch ($key) {
            case 'applicant_age':
                    if($application->employee_status == 'SALARIED' && $value >= 18 && $value <= 60){
                        return [true];
                    }else if(in_array($application->employee_status, ['Self Employed - Professional', 'Self Employed - Business', 'BUSINESS']) && $value >= 20 && $value <= 65){
                        return [true];
                    }
                break;
            case 'loan_term':
                if($value >= 3 && $value <= 36){
                    return [true];
                }
                return [false, true, [$value < 3 ? 'Loan Term is < 3 months' : 'Loan Term is > 36 months']];
                break;
            case 'monthly_income':
                if($application->employee_status == 'SALARIED' && $value >= 15000){
                    return [true];
                }elseif($application->employee_status == 'SALARIED'){
                    return [false, true, ['Monthly Income is <= 15,000']];
                }
                if(in_array($application->employee_status, ['Self Employed - Professional', 'Self Employed - Business', 'BUSINESS']) && $value >= 25000){
                    return [true];
                }elseif(in_array($application->employee_status, ['Self Employed - Professional', 'Self Employed - Business', 'BUSINESS'])){
                    return [false, true, ['Monthly Income is <= 25,000']];
                }
                break;
            case 'income_proof':
                if($application->employee_status == 'SALARIED'){
                    if(!in_array('itr', array_keys($value)) && $application->monthly_income >= 500000 && isset($application->creditReport[0]) && $application->creditReport[0]->Score < 700 && $application->loan_amount > 75000){
                        return [false, true, ['ITR Needed as Income is >= 500000']];
                    }

                    if(!in_array('salary_slip',array_keys($value))){
                        return [false, true, ['Salary Slip Needed']];
                    }

                    return [true];
                }else if(in_array($application->employee_status, ['Self Employed - Professional', 'Self Employed - Business', 'BUSINESS']) && !empty(array_intersect(['shop_act','gst_certificate','udyog_aadhaar_certificate','itr'], array_keys($value)))){
                    return [true];
                }else{
                    return [false, true, ['shop_act or gst_certificate or udyog_aadhaar_certificate or itr is needed']];
                }
                break;
            case 'loan_amount':
                $reasons = [];
                if($value >= 10000 && $value <= 2000000){
                    if($application->co_applicant_name){
                        return [true];
                    }else if(!$application->co_applicant_name && $application->employee_status == 'SALARIED' && $value >= 500000){
                        return [false, true, ['Add Co Applicant because Loan Amount is >= 500,000']];
                    }else if(!$application->co_applicant_name && in_array($application->employee_status, ['Self Employed - Professional', 'Self Employed - Business', 'BUSINESS']) && $value >= 400000){
                        return [false, true, ['Add Co Applicant because Loan Amount is >= 400,000']];
                    }else if(!$application->co_applicant_name && $application->employee_status == 'SALARIED' && isset($application->creditReport[0]) && $application->creditReport[0]->Score < 700 && $application->creditReport[0]->foirIncludingCFEMI > 60 && $value >= 300000){
                        return [false, true, ['Add Co Applicant because FOIR and/or Bureau Score is not as per Credit Policy']];
                    }else if(!$application->co_applicant_name && $application->employee_status == 'SALARIED' && isset($application->creditReport[0]) && $application->creditReport[0]->Score < 750 && $application->creditReport[0]->foirIncludingCFEMI > 50 && $value > 300000 && $value <= 400000){
                        return [false, true, ['Add Co Applicant because FOIR and/or Bureau Score is not as per Credit Policy']];
                    }else if(!$application->co_applicant_name && in_array($application->employee_status, ['Self Employed - Professional', 'Self Employed - Business', 'BUSINESS']) && isset($application->creditReport[0]) && $application->creditReport[0]->Score < 700 && $application->creditReport[0]->foirIncludingCFEMI > 60 && $value <= 400000){
                        return [false, true, ['Add Co Applicant because FOIR and/or Bureau Score is not as per Credit Policy']];
                    }
                }else{
                    $reasons[] = 'Loan Amount is < 10000 or Loan Amount > 20,00,000';
                }
                return [false, true, $reasons];
                break;
            case 'foir':
                if($value <= 75){
                    return [true];
                }else{
                    return [false, true, ['FOIR is > 75%']];
                }
                break;
            case 'credit_score':
                if($value >= 700){
                    return [true];
                }
                if($value >= -1 && $value <= 6 && !empty(array_intersect(['bank_statement','income proof'], array_keys($data[0])))){
                    return [true];
                }else if($value <= 700 && in_array('bank_statement', array_keys($data[0]))){
                    return [true];
                }else{
                    return [false, true];
                }
                break;
            case 'work_experience':
                if($application->employee_status == 'SALARIED' && $value >= 12) {
                    return [true];
                }else if($application->employee_status == 'SALARIED'){
                    return [false, true, ['Work stability at current company is < 1 Year']];
                }
                if(in_array($application->employee_status, ['Self Employed - Professional', 'Self Employed - Business', 'BUSINESS']) && $value >= 24){
                    return [true];
                }elseif(in_array($application->employee_status, ['Self Employed - Professional', 'Self Employed - Business', 'BUSINESS'])){
                    return [false, true, ['Work stability at current company is < 2 Years']];
                }
                break;
            case 'bank_statement_file':
                if($application->employee_status == 'SALARIED'){
                    if($application->loan_amount <= 75000) {
                        return [true];
                    }elseif($application->loan_amount > 75000){
                        return [true];
                    }
                }elseif(in_array($application->employee_status, ['Self Employed - Professional', 'Self Employed - Business', 'BUSINESS'])){
                    return [true];
                }
                break;
        }

        return [false];
    }

    public function AcceptableDataReason($key, $application, $other = false){
        $acceptableDataReason = AcceptableDataReason::where('application_id', $application->id)->first(['id',$key]);
        if($other){
            $key_variable = $key.'_other';
            $acceptableDataDrop = AcceptableDataReason::where('application_id', $application->id)->first(['id',$key_variable]);
            return ['Reason' => isset($acceptableDataReason->$key) ? $acceptableDataReason->$key : '', 'selectDropDownValue' => isset($acceptableDataDrop->$key_variable) ? $acceptableDataDrop->$key_variable : ''];
        }
        return isset($acceptableDataReason->$key) ? $acceptableDataReason->$key : '';
    }

    public function getProductName($product, $status = ''){
        if(!$product){
            return $product;
        }
        $data = explode(',', $product);
        $products = Products::whereIn('id', $data);
        if($status == 'approved'){
            $products = $products->withTrashed();
        }
        $products = $products->get(['name']);
        $productName = [];
        foreach ($products as $_product){
            $productName[] = $_product->name;
        }

        return $productName ? implode(',', $productName) : $product;
    }

    public function getVerificationStatusV1($docsList, $application, $verification, $pastLogs = array())
    {
        switch ($verification['key']) {

            case 'loan_term':
                if(isset($verification['view'])){
                    $_status = $this->AcceptableData($verification['key'], $application->tenure, $application);
                    $verification['view']['Acceptable'] = $_status[0];
                    $verification['view']['isMandatory'] = isset($_status[1]) ? $_status[1] : false;
                    $verification['view']['Errors'] = isset($_status[2]) ? $_status[2] : '';
                    $verification['view']['selectDropDown'] = [
                        'Good Customer Profile',
                        'As per Merchant/Customer Request',
                        'Other'
                    ];
                    $acceptableDataReason = $this->AcceptableDataReason($verification['key'], $application, true);
                    $verification['view']['selectDropDownValue'] = $acceptableDataReason['selectDropDownValue'];
                    $verification['view']['Reason'] = $acceptableDataReason['Reason'];
                }
                return (true) ? [isset($application->tenure) ? $application->tenure : '', true, $verification] : false;
                break;
            case 'monthly_income':
                if(isset($verification['view'])){
                    $_status = $this->AcceptableData($verification['key'], $application->monthly_income, $application);
                    $verification['view']['Acceptable'] = $_status[0];
                    $verification['view']['isMandatory'] = isset($_status[1]) ? $_status[1] : false;
                    $verification['view']['Errors'] = isset($_status[2]) ? $_status[2] : '';
                    $verification['view']['selectDropDown'] = [
                        'Co-Applicant Added',
                        'Good Repayment History',
                        'Has side Income',
                        'Strong Bank Balance',
                        'Other'
                    ];
                    $acceptableDataReason = $this->AcceptableDataReason($verification['key'], $application, true);
                    $verification['view']['selectDropDownValue'] = $acceptableDataReason['selectDropDownValue'];
                    $verification['view']['Reason'] = $acceptableDataReason['Reason'];
                }
                return (true) ? [isset($application->monthly_income) ? $application->monthly_income : '', true, $verification] : false;
                break;
            case 'income_proof':
                if(isset($verification['view'])){
                    $_status = $this->AcceptableData($verification['key'], $docsList, $application);
                    $verification['view']['Acceptable'] = $_status[0];
                    $verification['view']['isMandatory'] = isset($_status[1]) ? $_status[1] : false;
                    $verification['view']['Errors'] = isset($_status[2]) ? $_status[2] : '';
                    $verification['view']['selectDropDown'] = [
                        'Income Verified from bank statement',
                        'Does not have any Income Proof',
                        'Good Repayment History',
                        'EPF Verified',
                        'Other'
                    ];
                    $acceptableDataReason = $this->AcceptableDataReason($verification['key'], $application, true);
                    $verification['view']['selectDropDownValue'] = $acceptableDataReason['selectDropDownValue'];
                    $verification['view']['Reason'] = $acceptableDataReason['Reason'];
                    return (true) ? [$verification['view']['Acceptable'] ? 'Document uploaded' : '', true, $verification] : false;
                }
                return false;
                break;
            case 'loan_amount':
                if(isset($verification['view'])){
                    $_status = $this->AcceptableData($verification['key'], $application->approved_amount, $application);
                    $verification['view']['Acceptable'] = $_status[0];
                    $verification['view']['isMandatory'] = isset($_status[1]) ? $_status[1] : false;
                    $verification['view']['Errors'] = isset($_status[2]) ? $_status[2] : '';
                    $verification['view']['Reason'] = $this->AcceptableDataReason($verification['key'], $application);
                }
                return (true) ? [isset($application->approved_amount) ? $application->approved_amount : '', true, $verification] : false;
                break;
            case 'foir':
                if(isset($verification['view'])){
                    $request = new Request();
                    $request->attributes->add(['application_id'=>$application->id]);
                    $this->getScoreCard($request);
                    $updatedFoir = ConsumerApplication::with('creditReport')->where('id', $application->id)->first();
                    $foirIncludingCFEMI = isset($updatedFoir->creditReport) && isset($updatedFoir->creditReport[0]) ?
                        $updatedFoir->creditReport[0]->foirIncludingCFEMI :
                                                (isset($application->creditReport) && isset($application->creditReport[0]) ? $application->creditReport[0]->foirIncludingCFEMI : 0);
                    $_status = $this->AcceptableData($verification['key'], $foirIncludingCFEMI, $application);
                    $verification['view']['Acceptable'] = isset($application->creditReport) && isset($application->creditReport[0]) && isset($_status[0]) ? $_status[0] : false;
                    $verification['view']['isMandatory'] = isset($application->creditReport) && isset($application->creditReport[0]) && isset($_status[1]) ? $_status[1] : false;
                    if(!$foirIncludingCFEMI && isset($docsList[$verification['key']])){
                        $verification['view']['Acceptable'] = true;
                        $verification['view']['isMandatory'] = true;
                    }
                    $foirIncludingCFEMI = !$foirIncludingCFEMI ? (isset($docsList[$verification['key']]) ? 1 : 0) : $foirIncludingCFEMI;
                    $verification['view']['Errors'] = isset($_status[2]) ? $_status[2] : '';
                    $verification['view']['selectDropDown'] = [
                        'Co-Applicant Added',
                        'New FOIR Sheet attached',
                        'Good Repayment History',
                        'Other'
                    ];
                    $acceptableDataReason = $this->AcceptableDataReason($verification['key'], $application, true);
                    $verification['view']['selectDropDownValue'] = $acceptableDataReason['selectDropDownValue'];
                    $verification['view']['Reason'] = $acceptableDataReason['Reason'];
                }
                return (true) ? [(isset($application->creditReport[0]) && isset($foirIncludingCFEMI) ? round($foirIncludingCFEMI) : 'No Equifax'), true, $verification] : false;
                break;
            // case 'original_seen_verified':
            //     return ( isset($docsList['original_seen_verified'])) ? [$docsList['original_seen_verified'], true] : false;
            //     break;

            case 'product_verification':
                if(isset($verification['view'])){
                    $verification['view']['Reason'] = $this->AcceptableDataReason($verification['key'], $application);
                }
                return (true) ? [$verification['view']['Reason'], true, $verification] : false;
                break;
            case 'negative_profile':
                return (isset($application->application_element->negative_profile) && $application->application_element->negative_profile > 0) ? [$application->application_element->negative_profile, true] : false;
                break;
            case 'pan_validation':
                $isOnValidation = (isset($application->creditReport[0]) && isset($application->creditReport[0]->panValidation)) ? true : false;
                if ($isOnValidation) {
                    return ['', $isOnValidation];
                }
                return (isset($docsList['panvalidation'])) ? [$docsList['panvalidation'], true] : false;
                break;
            case 'customer_age':
                if ($application->dob != null && $application->dob != "1970-01-01") {
                    $age = (date('Y') - date('Y', strtotime($application->dob)));
                    return ($age > 20 && $age < 65) ? [$age, true] : false;
                }
                break;
            case 'blood_relative':
                if(isset($verification['view'])){
                    $verification['view']['Acceptable'] = $application->checklist->blood_relative ? true : false;
                    $verification['view']['isMandatory'] = !$application->checklist->blood_relative ? true : false;
                    $verification['view']['Errors'] = '';
                    $verification['view']['selectDropDown'] = [
                        'No Earning Family Member',
                        'Other',
                    ];
                    $acceptableDataReason = $this->AcceptableDataReason($verification['key'], $application, true);
                    $verification['view']['selectDropDownValue'] = $acceptableDataReason['selectDropDownValue'];
                    $verification['view']['Reason'] = $acceptableDataReason['Reason'];
                }
                return [($application->co_applicant_name ? $application->co_applicant_name : ''), true, $verification];
                break;
            case 'min_balance_charge':
                if(isset($verification['view'])){
                    $verification['view']['Acceptable'] = isset($application->checklist->min_balance_charge) && !empty($application->checklist->min_balance_charge) ? true : false;
                    $verification['view']['isMandatory'] = isset($application->checklist->min_balance_charge) && !empty($application->checklist->min_balance_charge) ? true : false;
                    $verification['view']['Errors'] = '';
                    $verification['view']['selectDropDown'] = [
                        'Co-Applicant Added',
                        'Other',
                    ];
                    $acceptableDataReason = $this->AcceptableDataReason($verification['key'], $application, true);
                    $verification['view']['selectDropDownValue'] = $acceptableDataReason['selectDropDownValue'];
                    $verification['view']['Reason'] = $acceptableDataReason['Reason'];
                }
                return [(isset($application->checklist->min_balance_charge) && !empty($application->checklist->min_balance_charge)) ? 'Yes' : 'No', true, $verification];
                break;
            case 'suspicious_file_input':
                $isFraud = $this->isFraud($application->id, 'fraud_report.json');
                if(isset($verification['view'])){
                    $verification['view']['Acceptable'] = $isFraud ? true : false;
                    $verification['view']['isMandatory'] = $isFraud ? true : false;
                    $verification['view']['Errors'] = '';
                    $verification['view']['selectDropDown'] = [
                        'Converted Bank St to PDF',
                        'Removed Password',
                        'Customer is not aware',
                        'Another Bank Statement taken',
                        'Other',
                    ];
                    $acceptableDataReason = $this->AcceptableDataReason($verification['key'], $application, true);
                    $verification['view']['selectDropDownValue'] = $acceptableDataReason['selectDropDownValue'];
                    $verification['view']['Reason'] = $acceptableDataReason['Reason'];
                }
                return [$isFraud ? 'Suspicious File Input' : 'No Suspicious File Input', true, $verification];
                //return (isset($application->checklist->min_balance_charge) && !empty($application->checklist->min_balance_charge)) ? [$application->checklist->min_balance_charge, true, $verification] : false;
                break;
            case 'reference_taken':
                return (isset($application->checklist->reference_taken) && !empty($application->checklist->reference_taken)) ? [$application->checklist->reference_taken, true] : false;
                break;
            case 'negative_profession':
                if(isset($verification['view']) && isset($application->checklist->negative_profession)){
                    $verification['view']['Acceptable'] = !empty($application->checklist->negative_profession) ? true : false;
                    $verification['view']['isMandatory'] = !empty($application->checklist->negative_profession) ? true : false;
                    $verification['view']['Errors'] = '';
                    $verification['view']['selectDropDown'] = [
                        'Good Repayment History',
                        'Stable Income',
                        'Strong Bank Balance',
                        'Other',
                    ];
                    $acceptableDataReason = $this->AcceptableDataReason($verification['key'], $application, true);
                    $verification['view']['selectDropDownValue'] = $acceptableDataReason['selectDropDownValue'];
                    $verification['view']['Reason'] = $acceptableDataReason['Reason'];
                    $negativeProfession = NegativeProfile::where('id',$application->checklist->negative_profession)->first(['name']);
                }
                return (isset($application->checklist->negative_profession) && !empty($application->checklist->negative_profession)) ? [isset($negativeProfession->name) ? $negativeProfession->name : $application->checklist->negative_profession, true, $verification] : false;
                break;
            case 'cpv_ic':
                return (isset($application->checklist->cpv_ic) && !empty($application->checklist->cpv_ic)) ? [$application->checklist->cpv_ic, true] : false;
                break;
            case 'utility_bill_verified':
                return (isset($application->checklist->utility_bill_verified) && !empty($application->checklist->utility_bill_verified)) ? [$application->checklist->utility_bill_verified, true] : false;
                break;
            case 'utility_bill_validated':
                    $idsCheck = ConsumerApplicationFiles::where('consumer_application_id', $application->id)->get(['id']);
                    $mainIds = [];
                    foreach ($idsCheck as $_id_p){
                        $mainIds[] = $_id_p->id;
                    }
                    if($mainIds) {
                        $utilityValidation = UtilityValidation::whereIn('consumer_application_file_id', $mainIds)->first(['id']);
                    }
                return (isset($utilityValidation->id)) ? ['Validated', true] : false;
                break;
            case 'pl_gl_taken':
                return (isset($application->checklist->pl_gl_taken) && !empty($application->checklist->pl_gl_taken)) ? [$application->checklist->pl_gl_taken, true] : false;
                break;
            case 'out_cb_eb':
                if(isset($verification['view'])){
                    $verification['view']['Acceptable'] =  isset($application->checklist->out_cb_eb) && !empty($application->checklist->out_cb_eb) ? true : false;
                    $verification['view']['isMandatory'] = isset($application->checklist->out_cb_eb) && !empty($application->checklist->out_cb_eb) ? true : false;
                    $verification['view']['selectDropDown'] = [
                        'Good Repayment History',
                        'Co-Applicant Added',
                        'Transfers to FD/Savings Account',
                        'Overdraft Facility',
                        'Other',
                    ];
                    $acceptableDataReason = $this->AcceptableDataReason($verification['key'], $application, true);
                    $verification['view']['selectDropDownValue'] = $acceptableDataReason['selectDropDownValue'];
                    $verification['view']['Reason'] = $acceptableDataReason['Reason'];
                }
                return [(isset($application->checklist->out_cb_eb) && !empty($application->checklist->out_cb_eb)) ? $application->checklist->out_cb_eb : '', true, $verification];
                break;
            case 'abb_emi':
                $times = 0;
                if($application->emi && $application->employee_status == 'SALARIED'){
                    if($application->emi->emi <= 25000){
                        $times = 2;
                    }elseif($application->emi->emi >= 25001 && $application->emi->emi < 50000){
                        $times = 2.5;
                    }elseif($application->emi->emi > 50000){
                        $times = 1.5;
                    }
                }else if($application->emi && in_array($application->employee_status, ['Self Employed - Professional', 'Self Employed - Business', 'BUSINESS'])){
                    if($application->emi->emi <= 25000){
                        $times = 2.5;
                    }elseif($application->emi->emi >= 25001 && $application->emi->emi < 50000){
                        $times = 3;
                    }elseif($application->emi->emi > 50000){
                        $times = 2;
                    }
                }


                if(isset($verification['view'])){
                    $verification['view']['Acceptable'] =  isset($application->checklist->abb_emi) && $application->checklist->abb_emi ? true : false;
                    $verification['view']['isMandatory'] = isset($application->checklist->abb_emi) && $application->checklist->abb_emi ? false : true;
                    $verification['view']['selectDropDown'] = [
                        'Good Repayment History',
                        'Co-Applicant Added',
                        'Transfers to FD/Savings Account',
                        'Overdraft Facility',
                        'Other',
                    ];
                    $acceptableDataReason = $this->AcceptableDataReason($verification['key'], $application, true);
                    $verification['view']['selectDropDownValue'] = $acceptableDataReason['selectDropDownValue'];
                    $verification['view']['Reason'] = $acceptableDataReason['Reason'];
                }
                return (true) ? [$times, true, $verification] : false;
            case 'in_cb':
                return (isset($application->checklist->in_cb) && !empty($application->checklist->in_cb)) ? [$application->checklist->in_cb, true] : false;
                break;
            case 'applicant_age':
                if ($application->dob != null && $application->dob != "1970-01-01") {
                    $age = (date('Y') - date('Y', strtotime($application->dob)));

                    if(isset($verification['view'])){
                        $_status = $this->AcceptableData($verification['key'], $age, $application);
                        $verification['view']['Acceptable'] = $_status[0];
                        $verification['view']['isMandatory'] = isset($_status[1]) ? $_status[1] : false;
                        $verification['view']['Errors'] = isset($_status[2]) ? $_status[2] : '';
                        $verification['view']['selectDropDown'] = [
                            'Co-Applicant Added',
                            'Steady Income',
                            'Other',
                        ];
                        $acceptableDataReason = $this->AcceptableDataReason($verification['key'], $application, true);
                        $verification['view']['selectDropDownValue'] = $acceptableDataReason['selectDropDownValue'];
                        $verification['view']['Reason'] = $acceptableDataReason['Reason'];
                    }
                    return true ? [$age ? $age : '', true, $verification] : false;
                }
                break;
            case 'linkedin':
                return (isset($application->checklist->linkedin) && !empty($application->checklist->linkedin)) ? [$application->checklist->linkedin, true] : false;
                break;
            case 'facebook':
                return (isset($application->checklist->facebook) && !empty($application->checklist->facebook)) ? [$application->checklist->facebook, true] : false;
                break;
            case 'tele_verification':
                return (isset($application->user->is_otp_verified) && ($application->user->is_otp_verified == 1)) ? [1, true] : ((isset($application->checklist->tele_verification) && $application->checklist->tele_verification == 1) ? [1, true] : false);
                break;
            case 'digio_kyc':
                $digio_kyc = KYCDetails::where('application_id', $application->id)->where('applicant_type', 1)->whereNotNull('response')->orderBy('id','desc')->first(['response','created_at']);
                return (isset($digio_kyc->response) && $digio_kyc->response) ? [1, true] : false;
                break;
            //    case 'onfido_kyc':
            //        $onfido_kyc = OnfidoIntegration::where('application_id', $application->id)->where('applicant_type', 1)->whereNotNull('data')->orderBy('created_at','desc')->first();
            //        return (isset($onfido_kyc->id) && isset($docsList['onfido_check_report'])) ? ['<span><a style="text-decoration: none;font-size: 14px;color: #737580;" href="/admin/consumer-applications/edit/'.$application->id.'"><i class="fa fa-eye"></i> View Report</a></span>', true] : false;
            //        break;
            case 'co_app_digio_kyc':
                $digio_kyc = KYCDetails::where('application_id', $application->id)->where('applicant_type', 2)->whereNotNull('response')->orderBy('id','desc')->first(['response','created_at']);
                return (isset($digio_kyc->response) && $digio_kyc->response) ? [1, true] : false;
                break;
            //    case 'co_app_onfido_kyc':
            //        $onfido_kyc = OnfidoIntegration::where('application_id', $application->id)->where('applicant_type', 2)->whereNotNull('data')->orderBy('created_at','desc')->first();
            //        return (isset($onfido_kyc->id) && isset($docsList['co_app_onfido_check_report'])) ? ['<span><a style="text-decoration: none;font-size: 14px;color: #737580;" href="/admin/consumer-applications/edit/'.$application->id.'"><i class="fa fa-eye"></i> View Report</a></span>', true] : false;
            //        break;
            case 'hyperverge_kyc':
                $flag = 0;
                if(self::VKYC_VENDOR == "karza") {
                    $karza = KarzaVideoAttribute::where('application_id', $application->id)->whereNull('deleted_at')->where('applicant_type',1)->first(['id']);
                    if(isset($karza->id) && !empty($karza->id)){
                        $webhook = KarzaVideoWebhook::where('karza_id', $karza->id)->first(['data', 'applicant_type']);
                        if ($webhook) {
                            $flag =1;
                        }
                    }
                }else {
                    $hyperverge = HypervergeVideoAttribute::where('application_id', $application->id)->where('applicant_type',1)->first(['id']);
                    if(isset($hyperverge->id) && !empty($hyperverge->id)){
                        $webhook = HypervergeWebhook::where('hyper_id', $hyperverge->id)->get(['data', 'applicant_type','event_type']);
                        foreach($webhook as $key=>$kyc_data) {
                            if(isset($kyc_data->event_type) && $kyc_data->event_type == 'vcip_kyc_status'){
                                $flag =1;
                            }
                        }
                    }
                }
                return ($flag == 1) ? [1, true] : false;
                break;
            case 'co_app_hyperverge_kyc':
                $is_kyc = 0;
                if(self::VKYC_VENDOR == "karza") {
                    $karza = KarzaVideoAttribute::where('application_id', $application->id)->whereNull('deleted_at')->where('applicant_type',2)->first(['id']);
                    if(isset($karza->id) && !empty($karza->id)){

                        $webhook = KarzaVideoWebhook::where('karza_id', $karza->id)->first(['data', 'applicant_type']);
                        if ($webhook) {
                            $is_kyc = 1;
                        }
                    }
                }else {
                    $hyperverge = HypervergeVideoAttribute::where('application_id', $application->id)->where('applicant_type',2)->first(['id']);
                    if(isset($hyperverge->id) && !empty($hyperverge->id)){

                        $webhook = HypervergeWebhook::where('hyper_id', $hyperverge->id)->get(['data', 'applicant_type','event_type']);
                        foreach($webhook as $key=>$kyc_data) {
                            if(isset($kyc_data->event_type) && $kyc_data->event_type == 'vcip_kyc_status'){
                                $is_kyc =1;
                            }
                        }
                    }
                }

                return ($is_kyc == 1) ? [1, true] : false;
                break;

            case 'call_recording':
                $callsLogs = CallLogs::where('_id', $application->id)->where('id_type', 'application_id')->where('purpose', 'verification_call')->whereNotNull('recording')->where('recording', '!=', '')->first(['id', 'recording', 'purpose']);
                if (!isset($callsLogs->id) && isset($docsList[$verification['key']])) {
                    $callsLogs = new \stdClass();
                    $callsLogs->recording = '/admin/consumer-application/get-documents/' . $docsList[$verification['key']];
                    $callsLogs->id = 1;
                    $callsLogs->purpose = 'Call Manually added';
                }
                return isset($callsLogs->id) ? ["<i class='fa fa-file-audio-o'></i> <a style='font-size: 12px;color:#7b7e8a;' href='" . $callsLogs->recording . "'>" . ucwords(str_replace('_', ' ', $callsLogs->purpose)) . " Call</a>", true] : false;
                break;
            case 'credit_score':
                if(isset($verification['view'])){
                    $Score = isset($application->creditReport[0]) ? $application->creditReport[0]->Score : '';
                    $_status = $this->AcceptableData($verification['key'], $Score, $application, [$docsList]);
                    $verification['view']['Acceptable'] = $_status[0];
                    $verification['view']['isMandatory'] = isset($_status[1]) && !$_status[1] ? true : false;
                    $verification['view']['Errors'] = isset($_status[2]) ? $_status[2] : '';
                    $verification['view']['selectDropDown'] = [
                        'CIBIL Score is Good',
                        'Co-Applicant Added',
                        'Good Repayment History',
                        'Other',
                    ];
                    $acceptableDataReason = $this->AcceptableDataReason($verification['key'], $application, true);
                    $verification['view']['selectDropDownValue'] = $acceptableDataReason['selectDropDownValue'];
                    $verification['view']['Reason'] = $acceptableDataReason['Reason'];
                }
                return [isset($Score) ? $Score : 'Report not generated', true, $verification];
                //return ['Report not generated', true, $verification];
                break;
            case 'work_experience':
                if(isset($verification['view'])){
                    $_status = $this->AcceptableData($verification['key'], $application->experience, $application);
                    $verification['view']['Acceptable'] = $_status[0];
                    $verification['view']['isMandatory'] = isset($_status[1]) ? $_status[1] : false;
                    $verification['view']['Errors'] = isset($_status[2]) ? $_status[2] : '';
                    $verification['view']['selectDropDown'] = [
                        '6 Months Exp + Salary slips taken',
                        '3 months Exp + Employed in Blue Chip Company/Govt Employee',
                        '18 Months in same business + Score > 750',
                        'EPF Verified',
                        'Other',
                    ];
                    $acceptableDataReason = $this->AcceptableDataReason($verification['key'], $application, true);
                    $verification['view']['selectDropDownValue'] = $acceptableDataReason['selectDropDownValue'];
                    $verification['view']['Reason'] = $acceptableDataReason['Reason'];
                }
                return [$_status[0] ? $application->experience : '', true, $verification];
                break;
            case 'bank_statement_file':
                $required_month = 0;
                if($application->employee_status == 'SALARIED'){
                    if($application->loan_amount <= 75000) {
                        $required_month = '3 Months';
                    }elseif($application->loan_amount > 75000){
                        $required_month = '6 Months';
                    }
                }elseif(in_array($application->employee_status, ['Self Employed - Professional', 'Self Employed - Business', 'BUSINESS'])){
                    $required_month = '6 Months';
                }
                if(isset($verification['view'])){
                    $_status = $this->AcceptableData($verification['key'], $application->experience, $application);
                    $verification['view']['Acceptable'] = isset($application->checklist->bank_statement_file) && $application->checklist->bank_statement_file ? true : false;//$_status[0];
                    $verification['view']['isMandatory'] = isset($application->checklist->bank_statement_file) && $application->checklist->bank_statement_file ? false : true;
                    $verification['view']['Errors'] = isset($_status[2]) ? $_status[2] : '';
                    $verification['view']['selectDropDown'] = [
                        'Good Repayment History',
                        'Other',
                    ];
                    $acceptableDataReason = $this->AcceptableDataReason($verification['key'], $application, true);
                    $verification['view']['selectDropDownValue'] = $acceptableDataReason['selectDropDownValue'];
                    $verification['view']['Reason'] = $acceptableDataReason['Reason'];
                }
                return [$required_month, true, $verification];
                break;
            case 'pan_card':
                if (isset($application->creditReport[0])) {
                    $PANIdsList = ($application->creditReport[0]->PANIdsList != null) ? json_decode($application->creditReport[0]->PANIdsList) : [];
                    return (in_array($application->pan_card, $PANIdsList)) ? [$application->pan_card, true] : false;
                }
                break;
            case 'aadhar':
                if (isset($application->creditReport[0])) {
                    $NationalIdsList = json_decode($application->creditReport[0]->NationalIdsList);
                    if (!$NationalIdsList) {
                        $NationalIdsList = [];
                    }
                    return (in_array(trim($application->aadhaar_card), $NationalIdsList)) ? [trim($application->aadhaar_card), true] : false;
                }
                break;
            case 'date_of_birth':
                if ($application->dob != null && $application->dob != "1970-01-01") {
                    if (isset($application->creditReport[0])) {
                        $DateOfBirth = date('Y-m-d', strtotime($application->creditReport[0]->DateOfBirth));
                        return (in_array(trim($application->dob), [$DateOfBirth])) ? [trim($application->dob), true] : false;
                    }
                }
                break;
            case 'dpd':
                $toBeCheck = [];
                $current_date = strtotime(date('Y-m-') . "01");
                $six_month = strtotime(date("Y-m-", strtotime("-12 months")) . "01");
                foreach ($application->foir as $foir) {
                    if ($foir->DateClosed == '' && $foir->applicant_type == 1) {
                        $dpds = json_decode($foir->dpd);
                        $lastDate = strtotime(date('Y-m-d', strtotime($foir->ReportedDate)));
                        if (!empty($dpds))
                            foreach ($dpds as $key => $dpd) {
                                if (!in_array($key, ['*', '000', 'CLSD', 'STD', 'NEW']) && ($lastDate >= $six_month) && ($lastDate <= $current_date)) {
                                    $toBeCheck[] = $dpd;
                                }
                            }
                    }
                }


                if(isset($verification['view'])){
                    $verification['view']['Acceptable'] = count($toBeCheck) > 0 && max(array_values($toBeCheck)) ? true : false;
                    $verification['view']['isMandatory'] = count($toBeCheck) > 0 && max(array_values($toBeCheck)) ? true : false;
                    $verification['view']['Errors'] = '';
                    $verification['view']['selectDropDown'] = [
                        'Cleared DPDs immediately',
                        'Overdue Receipt taken',
                        'False Reporting',
                        'Other',
                    ];
                    $acceptableDataReason = $this->AcceptableDataReason($verification['key'], $application, true);
                    $verification['view']['selectDropDownValue'] = $acceptableDataReason['selectDropDownValue'];
                    $verification['view']['Reason'] = $acceptableDataReason['Reason'];
                }
                return [(count($toBeCheck) > 0 ? max(array_values($toBeCheck)) : ''), true, $verification];
                break;
            case 'writeen_settled_suit':
                if(isset($verification['view'])){
                    $verification['view']['Acceptable'] = isset($application->checklist->writeen_settled_suit) && !empty($application->checklist->writeen_settled_suit) ? true : false;
                    $verification['view']['isMandatory'] = isset($application->checklist->writeen_settled_suit) && !empty($application->checklist->negative_profession) ? true : false;
                    $verification['view']['Errors'] = '';
                    $verification['view']['selectDropDown'] = [
                        'NOC Taken',
                        'False Reporting',
                        'Other',
                    ];
                    $acceptableDataReason = $this->AcceptableDataReason($verification['key'], $application, true);
                    $verification['view']['selectDropDownValue'] = $acceptableDataReason['selectDropDownValue'];
                    $verification['view']['Reason'] = $acceptableDataReason['Reason'];
                }
                return [(isset($application->checklist->writeen_settled_suit) && !empty($application->checklist->writeen_settled_suit)) ? $application->checklist->writeen_settled_suit : '', true, $verification];
                break;
            case 'enquiries':
                return (isset($application->creditReport[0]->Past12Months) && ($application->creditReport[0]->Past12Months > 0)) ? [$application->creditReport[0]->Past12Months, true] : false;
                break;
            case 'salary':
                if(isset($verification['view'])){
                    $verification['view']['Acceptable'] = isset($application->checklist->salary) && !empty($application->checklist->salary) ? true : false;
                    $verification['view']['isMandatory'] = isset($application->checklist->salary) && !empty($application->checklist->salary) ? false : true;
                    $verification['view']['Errors'] = '';
                    $verification['view']['selectDropDown'] = [
                        'Salary in Cash',
                        'Salary Certificate taken',
                        'Other',
                    ];
                    $acceptableDataReason = $this->AcceptableDataReason($verification['key'], $application, true);
                    $verification['view']['selectDropDownValue'] = $acceptableDataReason['selectDropDownValue'];
                    $verification['view']['Reason'] = $acceptableDataReason['Reason'];
                }
                return [(isset($application->checklist->salary) && !empty($application->checklist->salary)) ? $application->checklist->salary : '', true, $verification];
                break;
            case 'no_debit_chq_bounce_ecs':
                return (isset($application->checklist->no_debit_chq_bounce_ecs) && !empty($application->checklist->no_debit_chq_bounce_ecs)) ? [$application->checklist->no_debit_chq_bounce_ecs, true] : false;
                break;
            case 'regular_high_value':
                return (isset($application->checklist->regular_high_value) && !empty($application->checklist->regular_high_value)) ? [$application->checklist->regular_high_value, true] : false;
                break;
            case 'average_balance':
                return (isset($application->checklist->average_balance) && !empty($application->checklist->average_balance)) ? [$application->checklist->average_balance, true] : false;
                break;
            case 'mca':
                return (isset($docsList['mca'])) ? [$docsList['mca'], true] : false;
                break;
            case 'epf_uan':
                return (isset($docsList['epf-report'])) ? [$docsList['epf-report'], true] : false;
                break;
            case 'self_attested':
                return (isset($docsList['self_attested'])) ? [$docsList['self_attested'], true] : false;
                break;
            case 'prode':
                return (isset($docsList['prode42'])) ? [$docsList['prode42'], true] : false;
                break;
            case 'joining_date':
                return (isset($application->checklist->joining_date) && !empty($application->checklist->joining_date)) ? [date('m/Y', strtotime($application->checklist->joining_date)), true] : false;
                break;
            case 'designation':
                return (isset($application->application_element->designation) && !empty($application->application_element->designation)) ? [$application->application_element->designation, true] : false;
                break;
            case 'verify_pro_crt':
                return (isset($application->checklist->verify_pro_crt) && !empty($application->checklist->verify_pro_crt)) ? [$application->checklist->verify_pro_crt, true] : false;
                break;
            case 'official_email':
                return (isset($application->application_element->work_email) && !empty($application->application_element->work_email)) ? [$application->application_element->work_email, true] : false;
                break;
            case 'department':
                return (isset($application->application_element->department) && !empty($application->application_element->department)) ? [$application->application_element->department, true] : false;
                break;
            case 'contact':
                return (isset($application->application_element->contact) && !empty($application->application_element->contact)) ? [$application->application_element->contact, true] : false;
                break;
            case 'product_name':
                $productName = (isset($application->application_element) && !empty($application->application_element->product_name)) ? $application->application_element->product_name : '';
                $productName = $this->getProductName($productName);
                return $productName ? [$productName, true] : false;
                break;
            case 'office_address':
                return (isset($application->work_address_line_1) && !empty($application->work_address_line_1)) ? [$application->work_address_line_1, true] : false;
                break;
            case 'utility_bill':
                return (isset($docsList['utilitybillvalidation'])) ? [$docsList['utilitybillvalidation'], true] : false;
                break;
            case 'residing':
                $applicationData['consumer_applications'] = $application;
                $negativeArea = $this->getNegativeAreaList($applicationData);
                $isNegativeArea = (isset($application->checklist->residing) && !empty($application->checklist->residing)) ? $application->checklist->residing : ($negativeArea ? $negativeArea : false);
                return $isNegativeArea ? [$isNegativeArea, true] : false;
                break;
            case 'cpv':
                return (isset($docsList['cpv'])) ? [$docsList['cpv'], true] : false;
                break;
            case 'nach':
                $docs = array_reverse($docsList);
                foreach($docs as $key=>$doc){
                    if(stripos($key,'nach') !== false){
                        return [$doc, true];
                    }elseif(stripos($key,'mandate') !== false){
                        return [$doc, true];
                    }
                }
                return false;
                break;
                // $isNach = (isset($docsList['nach'])) ? [$docsList['nach'], true] : false;
                // if (!$isNach) {
                //     return (isset($application->mandate->id)) ? ['', true] : true;
                // }
                // return $isNach;

            case 'signed_loan_agreement':
                return (isset($docsList['loan_agreement_esign'])) ? [$docsList['loan_agreement_esign'], true] : false;
                break;
            case 'cheques':
                $docs = array_reverse($docsList);
                foreach($docs as $key=>$doc){
                    if($key == 'security_cheques'){
                        return [$doc, true];
                    }elseif($key == 'cheques'){
                        return [$doc, true];
                    }else{
                        continue;
                    }
                }
                return false;
                // return (isset($docsList['security_cheques'])) ? [$docsList['security_cheques'], true] : false;
                break;
            case 'credit_appraisal_memo':
                return (isset($docsList['credit_appraisal_memo'])) ? [$docsList['credit_appraisal_memo'], true] : false;
                break;
            case 'sanction_letter':
                return (isset($docsList['sanction_letter'])) ? [$docsList['sanction_letter'], true] : false;
                break;
            case 'advance_payment':
                if($application->merchant && $application->merchant->send_da_on_checklist){
                    return [asset('/admin/consumer-applications/edit/'.$application->id), true];
                }
                return (isset($docsList['pro_forma_invoice'])) ? [$docsList['pro_forma_invoice'], true] : false;
                break;
            case 'proform':
                if($application->merchant && $application->merchant->send_da_on_checklist){
                    return [asset('/admin/consumer-applications/edit/'.$application->id), true];
                }
                return (isset($docsList['proforma'])) ? [$docsList['proforma'], true] : false;
                break;
            case 'processing_fee':
                if ($application->emi && $application->emi->processing_fee > 0) {
                    $merchant = Merchant::where('id', $application->merchant_id)->first(['is_collected']);
                    $processing_fee_status = '<span style="font-size:12px;">Processing fee will be receive from merchant</span>';
                    if (isset($merchant->is_collected)) {
                        $proFormaInvoice = ProFormaInvoice::where('application_id', $application->id)->first(['processing_fee_by_merchant']);
                        if (($proFormaInvoice && is_null($proFormaInvoice->processing_fee_by_merchant) && $merchant->is_collected == 0) || (isset($proFormaInvoice->processing_fee_by_merchant) && $proFormaInvoice->processing_fee_by_merchant == 0)) {
                            if (isset($docsList['processing_fee_receipt'])) {
                                $processing_fee_status = '<span style="font-size:12px;"><a class="btn btn-primary col-md-12" href="/admin/consumer-application/get-documents/'.$docsList['processing_fee_receipt'].'" target="_blank">View Details</a></span>'; //Processing fee received from customer
                            } else if ((isset($_GET['state']) && $_GET['state'] == 'disbursement checklist done') || (!isset($_GET['state']) && $application->state != 'waiting for documents')) {
                                $accountingController = new AccountingController();
                                $processingDue = $accountingController->getApplicationDueAmount($application->id);
                                if ($processingDue['processing_fee_due'] > 0) {
                                    $t = "'Processing fee not received from customer'";
                                    $isRequired = '';
                                    $offer = MerchantOffers::where('id', $application->emi->offer_id)->first(['processing_fee_first_emi']);
                                    if (in_array('disbursement checklist done', $pastLogs)) {
                                        $isRequired = 'required="required"';
                                    }

                                    $isRequiredProcessingFee = 'required="required"';

                                    if(isset($offer->processing_fee_first_emi) && $offer->processing_fee_first_emi) {
                                        $processing_fee_status = '<span style="font-size:12px;">Processing Fees will be collected with 1st EMI</span>';
                                    }else{
                                        $processing_fee_status = '<i class="fa fa-exclamation-triangle" aria-hidden="true" style="margin-right: 6px;color: red;" title="Processing fee not received from customer"></i><input type="text" style="width: 0;height: 0;position: absolute;border: 0;outline: none;" oninvalid="this.setCustomValidity(' . $t . ')" name="pros" ' . $isRequired . ' '.$isRequiredProcessingFee.'/><span style="font-size:12px;color:red">Processing fee of Rs. ' . $processingDue['processing_fee_due'] . ' is pending from customer</span>';
                                    }
                                } else {
                                    $processing_fee_status = '<span style="font-size:12px;"><a href="javascript:void(0);" class="btn btn-primary col-md-12" data-toggle="modal" data-target="#viewProcessingFee">View Details</a></span>'; //Processing fee received from customer
                                }
                            }
                        }
                    }
                } else {
                    $processing_fee_status = '<span style="font-size:12px;">Processing fee is 0</span>';

                }
                return [$processing_fee_status, true];
                break;

        }
    }

    public function getVerificationStatus($docsList, $application, $verification, $pastLogs = array())
    {
        switch ($verification['key']) {

            case 'loan_term':
                if(isset($verification['view'])){
                    $_status = $this->AcceptableData($verification['key'], $application->tenure, $application);
                    $verification['view']['Acceptable'] = $_status[0];
                    $verification['view']['isMandatory'] = isset($_status[1]) ? $_status[1] : false;
                    $verification['view']['Errors'] = isset($_status[2]) ? $_status[2] : '';
                    $verification['view']['selectDropDown'] = [
                        'Good Customer Profile',
                        'As per Merchant/Customer Request',
                        'Other'
                    ];
                    $acceptableDataReason = $this->AcceptableDataReason($verification['key'], $application, true);
                    $verification['view']['selectDropDownValue'] = $acceptableDataReason['selectDropDownValue'];
                    $verification['view']['Reason'] = $acceptableDataReason['Reason'];
                }
                return (true) ? [isset($application->tenure) ? $application->tenure : '', true, $verification] : false;
                break;
            case 'monthly_income':
                if(isset($verification['view'])){
                    $_status = $this->AcceptableData($verification['key'], $application->monthly_income, $application);
                    $verification['view']['Acceptable'] = $_status[0];
                    $verification['view']['isMandatory'] = isset($_status[1]) ? $_status[1] : false;
                    $verification['view']['Errors'] = isset($_status[2]) ? $_status[2] : '';
                    $verification['view']['selectDropDown'] = [
                        'Co-Applicant Added',
                        'Good Repayment History',
                        'Has side Income',
                        'Strong Bank Balance',
                        'Other'
                    ];
                    $acceptableDataReason = $this->AcceptableDataReason($verification['key'], $application, true);
                    $verification['view']['selectDropDownValue'] = $acceptableDataReason['selectDropDownValue'];
                    $verification['view']['Reason'] = $acceptableDataReason['Reason'];
                }
                return (true) ? [isset($application->monthly_income) ? $application->monthly_income : '', true, $verification] : false;
                break;
            case 'income_proof':
                if(isset($verification['view'])){
                    $_status = $this->AcceptableData($verification['key'], $docsList, $application);
                    $verification['view']['Acceptable'] = $_status[0];
                    $verification['view']['isMandatory'] = isset($_status[1]) ? $_status[1] : false;
                    $verification['view']['Errors'] = isset($_status[2]) ? $_status[2] : '';
                    $verification['view']['selectDropDown'] = [
                        'Income Verified from bank statement',
                        'Does not have any Income Proof',
                        'Good Repayment History',
                        'EPF Verified',
                        'Other'
                    ];
                    $acceptableDataReason = $this->AcceptableDataReason($verification['key'], $application, true);
                    $verification['view']['selectDropDownValue'] = $acceptableDataReason['selectDropDownValue'];
                    $verification['view']['Reason'] = $acceptableDataReason['Reason'];
                    return (true) ? [$verification['view']['Acceptable'] ? 'Document uploaded' : '', true, $verification] : false;
                }
                return false;
                break;
            case 'loan_amount':
                if(isset($verification['view'])){
                    $_status = $this->AcceptableData($verification['key'], $application->approved_amount, $application);
                    $verification['view']['Acceptable'] = $_status[0];
                    $verification['view']['isMandatory'] = isset($_status[1]) ? $_status[1] : false;
                    $verification['view']['Errors'] = isset($_status[2]) ? $_status[2] : '';
                    $verification['view']['Reason'] = $this->AcceptableDataReason($verification['key'], $application);
                }
                return (true) ? [isset($application->approved_amount) ? $application->approved_amount : '', true, $verification] : false;
                break;
            case 'foir':
                if(isset($verification['view'])){
                    $request = new Request();
                    $request->attributes->add(['application_id'=>$application->id]);
                    $this->getScoreCard($request);
                    $updatedFoir = ConsumerApplication::with('creditReport')->where('id', $application->id)->first();
                    $foirIncludingCFEMI = isset($updatedFoir->creditReport) && isset($updatedFoir->creditReport[0]) ?
                        $updatedFoir->creditReport[0]->foirIncludingCFEMI :
                                                (isset($application->creditReport) && isset($application->creditReport[0]) ? $application->creditReport[0]->foirIncludingCFEMI : 0);
                    $_status = $this->AcceptableData($verification['key'], $foirIncludingCFEMI, $application);
                    $verification['view']['Acceptable'] = isset($application->creditReport) && isset($application->creditReport[0]) && isset($_status[0]) ? $_status[0] : false;
                    $verification['view']['isMandatory'] = isset($application->creditReport) && isset($application->creditReport[0]) && isset($_status[1]) ? $_status[1] : false;
                    if(!$foirIncludingCFEMI && isset($docsList[$verification['key']])){
                        $verification['view']['Acceptable'] = true;
                        $verification['view']['isMandatory'] = true;
                    }
                    $foirIncludingCFEMI = !$foirIncludingCFEMI ? (isset($docsList[$verification['key']]) ? 1 : 0) : $foirIncludingCFEMI;
                    $verification['view']['Errors'] = isset($_status[2]) ? $_status[2] : '';
                    $verification['view']['selectDropDown'] = [
                        'Co-Applicant Added',
                        'New FOIR Sheet attached',
                        'Good Repayment History',
                        'Other'
                    ];
                    $acceptableDataReason = $this->AcceptableDataReason($verification['key'], $application, true);
                    $verification['view']['selectDropDownValue'] = $acceptableDataReason['selectDropDownValue'];
                    $verification['view']['Reason'] = $acceptableDataReason['Reason'];
                }
                return (true) ? [(isset($application->creditReport[0]) && isset($foirIncludingCFEMI) ? round($foirIncludingCFEMI) : 'No Equifax'), true, $verification] : false;
                break;
            // case 'original_seen_verified':
            //     return ( isset($docsList['original_seen_verified'])) ? [$docsList['original_seen_verified'], true] : false;
            //     break;

            case 'product_verification':
                if(isset($verification['view'])){
                    $verification['view']['Reason'] = $this->AcceptableDataReason($verification['key'], $application);
                }
                return (true) ? [$verification['view']['Reason'], true, $verification] : false;
                break;
            case 'negative_profile':
                return (isset($application->application_element->negative_profile) && $application->application_element->negative_profile > 0) ? [$application->application_element->negative_profile, true] : false;
                break;
            case 'pan_validation':
                $isOnValidation = (isset($application->creditReport[0]) && isset($application->creditReport[0]->panValidation)) ? true : false;
                if ($isOnValidation) {
                    return ['', $isOnValidation];
                }
                return (isset($docsList['panvalidation'])) ? [$docsList['panvalidation'], true] : false;
                break;
            case 'customer_age':
                if ($application->dob != null && $application->dob != "1970-01-01") {
                    $age = (date('Y') - date('Y', strtotime($application->dob)));
                    return ($age > 20 && $age < 65) ? [$age, true] : false;
                }
                break;
            case 'blood_relative':
                if(isset($verification['view'])){
                    $verification['view']['Acceptable'] = $application->checklist->blood_relative ? true : false;
                    $verification['view']['isMandatory'] = !$application->checklist->blood_relative ? true : false;
                    $verification['view']['Errors'] = '';
                    $verification['view']['selectDropDown'] = [
                        'No Earning Family Member',
                        'Other',
                    ];
                    $acceptableDataReason = $this->AcceptableDataReason($verification['key'], $application, true);
                    $verification['view']['selectDropDownValue'] = $acceptableDataReason['selectDropDownValue'];
                    $verification['view']['Reason'] = $acceptableDataReason['Reason'];
                }
                return [($application->co_applicant_name ? $application->co_applicant_name : ''), true, $verification];
                break;
            case 'min_balance_charge':
                if(isset($verification['view'])){
                    $verification['view']['Acceptable'] = isset($application->checklist->min_balance_charge) && !empty($application->checklist->min_balance_charge) ? true : false;
                    $verification['view']['isMandatory'] = isset($application->checklist->min_balance_charge) && !empty($application->checklist->min_balance_charge) ? true : false;
                    $verification['view']['Errors'] = '';
                    $verification['view']['selectDropDown'] = [
                        'Co-Applicant Added',
                        'Other',
                    ];
                    $acceptableDataReason = $this->AcceptableDataReason($verification['key'], $application, true);
                    $verification['view']['selectDropDownValue'] = $acceptableDataReason['selectDropDownValue'];
                    $verification['view']['Reason'] = $acceptableDataReason['Reason'];
                }
                return [(isset($application->checklist->min_balance_charge) && !empty($application->checklist->min_balance_charge)) ? 'Yes' : 'No', true, $verification];
                break;
            case 'suspicious_file_input':
                $isFraud = $this->isFraud($application->id, 'fraud_report.json');
                if(isset($verification['view'])){
                    $verification['view']['Acceptable'] = $isFraud ? true : false;
                    $verification['view']['isMandatory'] = $isFraud ? true : false;
                    $verification['view']['Errors'] = '';
                    $verification['view']['selectDropDown'] = [
                        'Converted Bank St to PDF',
                        'Removed Password',
                        'Customer is not aware',
                        'Another Bank Statement taken',
                        'Other',
                    ];
                    $acceptableDataReason = $this->AcceptableDataReason($verification['key'], $application, true);
                    $verification['view']['selectDropDownValue'] = $acceptableDataReason['selectDropDownValue'];
                    $verification['view']['Reason'] = $acceptableDataReason['Reason'];
                }
                return [$isFraud ? 'Suspicious File Input' : 'No Suspicious File Input', true, $verification];
                //return (isset($application->checklist->min_balance_charge) && !empty($application->checklist->min_balance_charge)) ? [$application->checklist->min_balance_charge, true, $verification] : false;
                break;
            case 'reference_taken':
                return (isset($application->checklist->reference_taken) && !empty($application->checklist->reference_taken)) ? [$application->checklist->reference_taken, true] : false;
                break;
            case 'negative_profession':
                if(isset($verification['view']) && isset($application->checklist->negative_profession)){
                    $verification['view']['Acceptable'] = !empty($application->checklist->negative_profession) ? true : false;
                    $verification['view']['isMandatory'] = !empty($application->checklist->negative_profession) ? true : false;
                    $verification['view']['Errors'] = '';
                    $verification['view']['selectDropDown'] = [
                        'Good Repayment History',
                        'Stable Income',
                        'Strong Bank Balance',
                        'Other',
                    ];
                    $acceptableDataReason = $this->AcceptableDataReason($verification['key'], $application, true);
                    $verification['view']['selectDropDownValue'] = $acceptableDataReason['selectDropDownValue'];
                    $verification['view']['Reason'] = $acceptableDataReason['Reason'];
                    $negativeProfession = NegativeProfile::where('id',$application->checklist->negative_profession)->first(['name']);
                }
                return (isset($application->checklist->negative_profession) && !empty($application->checklist->negative_profession)) ? [isset($negativeProfession->name) ? $negativeProfession->name : $application->checklist->negative_profession, true, $verification] : false;
                break;
            case 'cpv_ic':
                return (isset($application->checklist->cpv_ic) && !empty($application->checklist->cpv_ic)) ? [$application->checklist->cpv_ic, true] : false;
                break;
            case 'utility_bill_verified':
                return (isset($application->checklist->utility_bill_verified) && !empty($application->checklist->utility_bill_verified)) ? [$application->checklist->utility_bill_verified, true] : false;
                break;
            case 'utility_bill_validated':
                    $idsCheck = ConsumerApplicationFiles::where('consumer_application_id', $application->id)->get(['id']);
                    $mainIds = [];
                    foreach ($idsCheck as $_id_p){
                        $mainIds[] = $_id_p->id;
                    }
                    if($mainIds) {
                        $utilityValidation = UtilityValidation::whereIn('consumer_application_file_id', $mainIds)->first(['id']);
                    }
                return (isset($utilityValidation->id)) ? ['Validated', true] : false;
                break;
            case 'pl_gl_taken':
                return (isset($application->checklist->pl_gl_taken) && !empty($application->checklist->pl_gl_taken)) ? [$application->checklist->pl_gl_taken, true] : false;
                break;
            case 'out_cb_eb':
                if(isset($verification['view'])){
                    $verification['view']['Acceptable'] =  isset($application->checklist->out_cb_eb) && !empty($application->checklist->out_cb_eb) ? true : false;
                    $verification['view']['isMandatory'] = isset($application->checklist->out_cb_eb) && !empty($application->checklist->out_cb_eb) ? true : false;
                    $verification['view']['selectDropDown'] = [
                        'Good Repayment History',
                        'Co-Applicant Added',
                        'Transfers to FD/Savings Account',
                        'Overdraft Facility',
                        'Other',
                    ];
                    $acceptableDataReason = $this->AcceptableDataReason($verification['key'], $application, true);
                    $verification['view']['selectDropDownValue'] = $acceptableDataReason['selectDropDownValue'];
                    $verification['view']['Reason'] = $acceptableDataReason['Reason'];
                }
                return [(isset($application->checklist->out_cb_eb) && !empty($application->checklist->out_cb_eb)) ? $application->checklist->out_cb_eb : '', true, $verification];
                break;
            case 'abb_emi':
                $times = 0;
                if($application->emi && $application->employee_status == 'SALARIED'){
                    if($application->emi->emi <= 25000){
                        $times = 2;
                    }elseif($application->emi->emi >= 25001 && $application->emi->emi < 50000){
                        $times = 2.5;
                    }elseif($application->emi->emi > 50000){
                        $times = 1.5;
                    }
                }else if($application->emi && in_array($application->employee_status, ['Self Employed - Professional', 'Self Employed - Business', 'BUSINESS'])){
                    if($application->emi->emi <= 25000){
                        $times = 2.5;
                    }elseif($application->emi->emi >= 25001 && $application->emi->emi < 50000){
                        $times = 3;
                    }elseif($application->emi->emi > 50000){
                        $times = 2;
                    }
                }


                if(isset($verification['view'])){
                    $verification['view']['Acceptable'] =  isset($application->checklist->abb_emi) && $application->checklist->abb_emi ? true : false;
                    $verification['view']['isMandatory'] = isset($application->checklist->abb_emi) && $application->checklist->abb_emi ? false : true;
                    $verification['view']['selectDropDown'] = [
                        'Good Repayment History',
                        'Co-Applicant Added',
                        'Transfers to FD/Savings Account',
                        'Overdraft Facility',
                        'Other',
                    ];
                    $acceptableDataReason = $this->AcceptableDataReason($verification['key'], $application, true);
                    $verification['view']['selectDropDownValue'] = $acceptableDataReason['selectDropDownValue'];
                    $verification['view']['Reason'] = $acceptableDataReason['Reason'];
                }
                return (true) ? [$times, true, $verification] : false;
            case 'in_cb':
                return (isset($application->checklist->in_cb) && !empty($application->checklist->in_cb)) ? [$application->checklist->in_cb, true] : false;
                break;
            case 'applicant_age':
                if ($application->dob != null && $application->dob != "1970-01-01") {
                    $age = (date('Y') - date('Y', strtotime($application->dob)));

                    if(isset($verification['view'])){
                        $_status = $this->AcceptableData($verification['key'], $age, $application);
                        $verification['view']['Acceptable'] = $_status[0];
                        $verification['view']['isMandatory'] = isset($_status[1]) ? $_status[1] : false;
                        $verification['view']['Errors'] = isset($_status[2]) ? $_status[2] : '';
                        $verification['view']['selectDropDown'] = [
                            'Co-Applicant Added',
                            'Steady Income',
                            'Other',
                        ];
                        $acceptableDataReason = $this->AcceptableDataReason($verification['key'], $application, true);
                        $verification['view']['selectDropDownValue'] = $acceptableDataReason['selectDropDownValue'];
                        $verification['view']['Reason'] = $acceptableDataReason['Reason'];
                    }
                    return true ? [$age ? $age : '', true, $verification] : false;
                }
                break;
            case 'linkedin':
                return (isset($application->checklist->linkedin) && !empty($application->checklist->linkedin)) ? [$application->checklist->linkedin, true] : false;
                break;
            case 'facebook':
                return (isset($application->checklist->facebook) && !empty($application->checklist->facebook)) ? [$application->checklist->facebook, true] : false;
                break;
            case 'tele_verification':
                return (isset($application->user->is_otp_verified) && ($application->user->is_otp_verified == 1)) ? [1, true] : ((isset($application->checklist->tele_verification) && $application->checklist->tele_verification == 1) ? [1, true] : false);
                break;
            case 'digio_kyc':
                $digio_kyc = KYCDetails::where('application_id', $application->id)->where('applicant_type', 1)->whereNotNull('response')->orderBy('id','desc')->first(['response','created_at']);
                return (isset($digio_kyc->response) && $digio_kyc->response) ? [1, true] : false;
                break;
            //    case 'onfido_kyc':
            //        $onfido_kyc = OnfidoIntegration::where('application_id', $application->id)->where('applicant_type', 1)->whereNotNull('data')->orderBy('created_at','desc')->first();
            //        return (isset($onfido_kyc->id) && isset($docsList['onfido_check_report'])) ? ['<span><a style="text-decoration: none;font-size: 14px;color: #737580;" href="/admin/consumer-applications/edit/'.$application->id.'"><i class="fa fa-eye"></i> View Report</a></span>', true] : false;
            //        break;
            case 'co_app_digio_kyc':
                $digio_kyc = KYCDetails::where('application_id', $application->id)->where('applicant_type', 2)->whereNotNull('response')->orderBy('id','desc')->first(['response','created_at']);
                return (isset($digio_kyc->response) && $digio_kyc->response) ? [1, true] : false;
                break;
            //    case 'co_app_onfido_kyc':
            //        $onfido_kyc = OnfidoIntegration::where('application_id', $application->id)->where('applicant_type', 2)->whereNotNull('data')->orderBy('created_at','desc')->first();
            //        return (isset($onfido_kyc->id) && isset($docsList['co_app_onfido_check_report'])) ? ['<span><a style="text-decoration: none;font-size: 14px;color: #737580;" href="/admin/consumer-applications/edit/'.$application->id.'"><i class="fa fa-eye"></i> View Report</a></span>', true] : false;
            //        break;
            case 'hyperverge_kyc':
                $flag = 0;
                if(self::VKYC_VENDOR == "karza") {
                    $karza = KarzaVideoAttribute::where('application_id', $application->id)->whereNull('deleted_at')->where('applicant_type',1)->first(['id']);
                    if(isset($karza->id) && !empty($karza->id)){
                        $webhook = KarzaVideoWebhook::where('karza_id', $karza->id)->first(['data', 'applicant_type']);
                        if ($webhook) {
                            $flag =1;
                        }
                    }
                }else {
                    $hyperverge = HypervergeVideoAttribute::where('application_id', $application->id)->where('applicant_type',1)->first(['id']);
                    if(isset($hyperverge->id) && !empty($hyperverge->id)){
                        $webhook = HypervergeWebhook::where('hyper_id', $hyperverge->id)->get(['data', 'applicant_type','event_type']);
                        foreach($webhook as $key=>$kyc_data) {
                            if(isset($kyc_data->event_type) && $kyc_data->event_type == 'vcip_kyc_status'){
                                $flag =1;
                            }
                        }
                    }
                }
                return ($flag == 1) ? [1, true] : false;
                break;
            case 'co_app_hyperverge_kyc':
                $is_kyc = 0;
                if(self::VKYC_VENDOR == "karza") {
                    $karza = KarzaVideoAttribute::where('application_id', $application->id)->whereNull('deleted_at')->where('applicant_type',2)->first(['id']);
                    if(isset($karza->id) && !empty($karza->id)){

                        $webhook = KarzaVideoWebhook::where('karza_id', $karza->id)->first(['data', 'applicant_type']);
                        if ($webhook) {
                            $is_kyc = 1;
                        }
                    }
                }else {
                    $hyperverge = HypervergeVideoAttribute::where('application_id', $application->id)->where('applicant_type',2)->first(['id']);
                    if(isset($hyperverge->id) && !empty($hyperverge->id)){

                        $webhook = HypervergeWebhook::where('hyper_id', $hyperverge->id)->get(['data', 'applicant_type','event_type']);
                        foreach($webhook as $key=>$kyc_data) {
                            if(isset($kyc_data->event_type) && $kyc_data->event_type == 'vcip_kyc_status'){
                                $is_kyc =1;
                            }
                        }
                    }
                }

                return ($is_kyc == 1) ? [1, true] : false;
                break;

            case 'call_recording':
                $callsLogs = CallLogs::where('_id', $application->id)->where('id_type', 'application_id')->where('purpose', 'verification_call')->whereNotNull('recording')->where('recording', '!=', '')->first(['id', 'recording', 'purpose']);
                if (!isset($callsLogs->id) && isset($docsList[$verification['key']])) {
                    $callsLogs = new \stdClass();
                    $callsLogs->recording = '/admin/consumer-application/get-documents/' . $docsList[$verification['key']];
                    $callsLogs->id = 1;
                    $callsLogs->purpose = 'Call Manually added';
                }
                return isset($callsLogs->id) ? ["<i class='fa fa-file-audio-o'></i> <a style='font-size: 12px;color:#7b7e8a;' href='" . $callsLogs->recording . "'>" . ucwords(str_replace('_', ' ', $callsLogs->purpose)) . " Call</a>", true] : false;
                break;
            case 'credit_score':
                if(isset($verification['view'])){
                    $Score = isset($application->creditReport[0]) ? $application->creditReport[0]->Score : '';
                    $_status = $this->AcceptableData($verification['key'], $Score, $application, [$docsList]);
                    $verification['view']['Acceptable'] = $_status[0];
                    $verification['view']['isMandatory'] = isset($_status[1]) && !$_status[1] ? true : false;
                    $verification['view']['Errors'] = isset($_status[2]) ? $_status[2] : '';
                    $verification['view']['selectDropDown'] = [
                        'CIBIL Score is Good',
                        'Co-Applicant Added',
                        'Good Repayment History',
                        'Other',
                    ];
                    $acceptableDataReason = $this->AcceptableDataReason($verification['key'], $application, true);
                    $verification['view']['selectDropDownValue'] = $acceptableDataReason['selectDropDownValue'];
                    $verification['view']['Reason'] = $acceptableDataReason['Reason'];
                }
                return [isset($Score) ? $Score : 'Report not generated', true, $verification];
                //return ['Report not generated', true, $verification];
                break;
            case 'work_experience':
                if(isset($verification['view'])){
                    $_status = $this->AcceptableData($verification['key'], $application->experience, $application);
                    $verification['view']['Acceptable'] = $_status[0];
                    $verification['view']['isMandatory'] = isset($_status[1]) ? $_status[1] : false;
                    $verification['view']['Errors'] = isset($_status[2]) ? $_status[2] : '';
                    $verification['view']['selectDropDown'] = [
                        '6 Months Exp + Salary slips taken',
                        '3 months Exp + Employed in Blue Chip Company/Govt Employee',
                        '18 Months in same business + Score > 750',
                        'EPF Verified',
                        'Other',
                    ];
                    $acceptableDataReason = $this->AcceptableDataReason($verification['key'], $application, true);
                    $verification['view']['selectDropDownValue'] = $acceptableDataReason['selectDropDownValue'];
                    $verification['view']['Reason'] = $acceptableDataReason['Reason'];
                }
                return [$_status[0] ? $application->experience : '', true, $verification];
                break;
            case 'bank_statement_file':
                $required_month = 0;
                if($application->employee_status == 'SALARIED'){
                    if($application->loan_amount <= 75000) {
                        $required_month = '3 Months';
                    }elseif($application->loan_amount > 75000){
                        $required_month = '6 Months';
                    }
                }elseif(in_array($application->employee_status, ['Self Employed - Professional', 'Self Employed - Business', 'BUSINESS'])){
                    $required_month = '6 Months';
                }
                if(isset($verification['view'])){
                    $_status = $this->AcceptableData($verification['key'], $application->experience, $application);
                    $verification['view']['Acceptable'] = isset($application->checklist->bank_statement_file) && $application->checklist->bank_statement_file ? true : false;//$_status[0];
                    $verification['view']['isMandatory'] = isset($application->checklist->bank_statement_file) && $application->checklist->bank_statement_file ? false : true;
                    $verification['view']['Errors'] = isset($_status[2]) ? $_status[2] : '';
                    $verification['view']['selectDropDown'] = [
                        'Good Repayment History',
                        'Other',
                    ];
                    $acceptableDataReason = $this->AcceptableDataReason($verification['key'], $application, true);
                    $verification['view']['selectDropDownValue'] = $acceptableDataReason['selectDropDownValue'];
                    $verification['view']['Reason'] = $acceptableDataReason['Reason'];
                }
                return [$required_month, true, $verification];
                break;
            case 'pan_card':
                if (isset($application->creditReport[0])) {
                    $PANIdsList = ($application->creditReport[0]->PANIdsList != null) ? json_decode($application->creditReport[0]->PANIdsList) : [];
                    return (in_array($application->pan_card, $PANIdsList)) ? [$application->pan_card, true] : false;
                }
                break;
            case 'aadhar':
                if (isset($application->creditReport[0])) {
                    $NationalIdsList = json_decode($application->creditReport[0]->NationalIdsList);
                    if (!$NationalIdsList) {
                        $NationalIdsList = [];
                    }
                    return (in_array(trim($application->aadhaar_card), $NationalIdsList)) ? [trim($application->aadhaar_card), true] : false;
                }
                break;
            case 'date_of_birth':
                if ($application->dob != null && $application->dob != "1970-01-01") {
                    if (isset($application->creditReport[0])) {
                        $DateOfBirth = date('Y-m-d', strtotime($application->creditReport[0]->DateOfBirth));
                        return (in_array(trim($application->dob), [$DateOfBirth])) ? [trim($application->dob), true] : false;
                    }
                }
                break;
            case 'dpd':
                $toBeCheck = [];
                $current_date = strtotime(date('Y-m-') . "01");
                $six_month = strtotime(date("Y-m-", strtotime("-12 months")) . "01");
                foreach ($application->foir as $foir) {
                    if ($foir->DateClosed == '' && $foir->applicant_type == 1) {
                        $dpds = json_decode($foir->dpd);
                        $lastDate = strtotime(date('Y-m-d', strtotime($foir->ReportedDate)));
                        if (!empty($dpds))
                            foreach ($dpds as $key => $dpd) {
                                if (!in_array($key, ['*', '000', 'CLSD', 'STD', 'NEW']) && ($lastDate >= $six_month) && ($lastDate <= $current_date)) {
                                    $toBeCheck[] = $dpd;
                                }
                            }
                    }
                }


                if(isset($verification['view'])){
                    $verification['view']['Acceptable'] = count($toBeCheck) > 0 && max(array_values($toBeCheck)) ? true : false;
                    $verification['view']['isMandatory'] = count($toBeCheck) > 0 && max(array_values($toBeCheck)) ? true : false;
                    $verification['view']['Errors'] = '';
                    $verification['view']['selectDropDown'] = [
                        'Cleared DPDs immediately',
                        'Overdue Receipt taken',
                        'False Reporting',
                        'Other',
                    ];
                    $acceptableDataReason = $this->AcceptableDataReason($verification['key'], $application, true);
                    $verification['view']['selectDropDownValue'] = $acceptableDataReason['selectDropDownValue'];
                    $verification['view']['Reason'] = $acceptableDataReason['Reason'];
                }
                return [(count($toBeCheck) > 0 ? max(array_values($toBeCheck)) : ''), true, $verification];
                break;
            case 'writeen_settled_suit':
                if(isset($verification['view'])){
                    $verification['view']['Acceptable'] = isset($application->checklist->writeen_settled_suit) && !empty($application->checklist->writeen_settled_suit) ? true : false;
                    $verification['view']['isMandatory'] = isset($application->checklist->writeen_settled_suit) && !empty($application->checklist->negative_profession) ? true : false;
                    $verification['view']['Errors'] = '';
                    $verification['view']['selectDropDown'] = [
                        'NOC Taken',
                        'False Reporting',
                        'Other',
                    ];
                    $acceptableDataReason = $this->AcceptableDataReason($verification['key'], $application, true);
                    $verification['view']['selectDropDownValue'] = $acceptableDataReason['selectDropDownValue'];
                    $verification['view']['Reason'] = $acceptableDataReason['Reason'];
                }
                return [(isset($application->checklist->writeen_settled_suit) && !empty($application->checklist->writeen_settled_suit)) ? $application->checklist->writeen_settled_suit : '', true, $verification];
                break;
            case 'enquiries':
                return (isset($application->creditReport[0]->Past12Months) && ($application->creditReport[0]->Past12Months > 0)) ? [$application->creditReport[0]->Past12Months, true] : false;
                break;
            case 'salary':
                if(isset($verification['view'])){
                    $verification['view']['Acceptable'] = isset($application->checklist->salary) && !empty($application->checklist->salary) ? true : false;
                    $verification['view']['isMandatory'] = isset($application->checklist->salary) && !empty($application->checklist->salary) ? false : true;
                    $verification['view']['Errors'] = '';
                    $verification['view']['selectDropDown'] = [
                        'Salary in Cash',
                        'Salary Certificate taken',
                        'Other',
                    ];
                    $acceptableDataReason = $this->AcceptableDataReason($verification['key'], $application, true);
                    $verification['view']['selectDropDownValue'] = $acceptableDataReason['selectDropDownValue'];
                    $verification['view']['Reason'] = $acceptableDataReason['Reason'];
                }
                return [(isset($application->checklist->salary) && !empty($application->checklist->salary)) ? $application->checklist->salary : '', true, $verification];
                break;
            case 'no_debit_chq_bounce_ecs':
                return (isset($application->checklist->no_debit_chq_bounce_ecs) && !empty($application->checklist->no_debit_chq_bounce_ecs)) ? [$application->checklist->no_debit_chq_bounce_ecs, true] : false;
                break;
            case 'regular_high_value':
                return (isset($application->checklist->regular_high_value) && !empty($application->checklist->regular_high_value)) ? [$application->checklist->regular_high_value, true] : false;
                break;
            case 'average_balance':
                return (isset($application->checklist->average_balance) && !empty($application->checklist->average_balance)) ? [$application->checklist->average_balance, true] : false;
                break;
            case 'mca':
                return (isset($docsList['mca'])) ? [$docsList['mca'], true] : false;
                break;
            case 'epf_uan':
                return (isset($docsList['epf-report'])) ? [$docsList['epf-report'], true] : false;
                break;
            case 'self_attested':
                return (isset($docsList['self_attested'])) ? [$docsList['self_attested'], true] : false;
                break;
            case 'prode':
                return (isset($docsList['prode42'])) ? [$docsList['prode42'], true] : false;
                break;
            case 'joining_date':
                return (isset($application->checklist->joining_date) && !empty($application->checklist->joining_date)) ? [date('m/Y', strtotime($application->checklist->joining_date)), true] : false;
                break;
            case 'designation':
                return (isset($application->application_element->designation) && !empty($application->application_element->designation)) ? [$application->application_element->designation, true] : false;
                break;
            case 'verify_pro_crt':
                return (isset($application->checklist->verify_pro_crt) && !empty($application->checklist->verify_pro_crt)) ? [$application->checklist->verify_pro_crt, true] : false;
                break;
            case 'official_email':
                return (isset($application->application_element->work_email) && !empty($application->application_element->work_email)) ? [$application->application_element->work_email, true] : false;
                break;
            case 'department':
                return (isset($application->application_element->department) && !empty($application->application_element->department)) ? [$application->application_element->department, true] : false;
                break;
            case 'contact':
                return (isset($application->application_element->contact) && !empty($application->application_element->contact)) ? [$application->application_element->contact, true] : false;
                break;
            case 'product_name':
                $productName = (isset($application->application_element) && !empty($application->application_element->product_name)) ? $application->application_element->product_name : '';
                $productName = $this->getProductName($productName);
                return $productName ? [$productName, true] : false;
                break;
            case 'office_address':
                return (isset($application->work_address_line_1) && !empty($application->work_address_line_1)) ? [$application->work_address_line_1, true] : false;
                break;
            case 'utility_bill':
                return (isset($docsList['utilitybillvalidation'])) ? [$docsList['utilitybillvalidation'], true] : false;
                break;
            case 'residing':
                $applicationData['consumer_applications'] = $application;
                $negativeArea = $this->getNegativeAreaList($applicationData);
                $isNegativeArea = (isset($application->checklist->residing) && !empty($application->checklist->residing)) ? $application->checklist->residing : ($negativeArea ? $negativeArea : false);
                return $isNegativeArea ? [$isNegativeArea, true] : false;
                break;
            case 'cpv':
                return (isset($docsList['cpv'])) ? [$docsList['cpv'], true] : false;
                break;
            case 'nach':
                $docs = array_reverse($docsList);
                foreach($docs as $key=>$doc){
                    if(stripos($key,'nach') !== false){
                        return [$doc, true];
                    }elseif(stripos($key,'mandate') !== false){
                        return [$doc, true];
                    }
                }
                return false;
                break;
                // $isNach = (isset($docsList['nach'])) ? [$docsList['nach'], true] : false;
                // if (!$isNach) {
                //     return (isset($application->mandate->id)) ? ['', true] : true;
                // }
                // return $isNach;

            case 'signed_loan_agreement':
                return (isset($docsList['loan_agreement_esign'])) ? [$docsList['loan_agreement_esign'], true] : false;
                break;
            case 'cheques':
                $docs = array_reverse($docsList);
                foreach($docs as $key=>$doc){
                    if($key == 'security_cheques'){
                        return [$doc, true];
                    }elseif($key == 'cheques'){
                        return [$doc, true];
                    }else{
                        continue;
                    }
                }
                return false;
                // return (isset($docsList['security_cheques'])) ? [$docsList['security_cheques'], true] : false;
                break;
            case 'credit_appraisal_memo':
                return (isset($docsList['credit_appraisal_memo'])) ? [$docsList['credit_appraisal_memo'], true] : false;
                break;
            case 'sanction_letter':
                return (isset($docsList['sanction_letter'])) ? [$docsList['sanction_letter'], true] : false;
                break;
            case 'advance_payment':
//                if($application->merchant && $application->merchant->send_da_on_checklist){
//                    return [asset('/admin/consumer-applications/edit/'.$application->id), true];
//                }
                return (isset($docsList['pro_forma_invoice'])) ? [$docsList['pro_forma_invoice'], true] : false;
                break;
            case 'proform':
                if($application->merchant && $application->merchant->send_da_on_checklist){
                    return [asset('/admin/consumer-applications/edit/'.$application->id), true];
                }
                return (isset($docsList['proforma'])) ? [$docsList['proforma'], true] : false;
                break;
            case 'solar_installation_proof':
                if ($application->merchant->disb_post_installation){
                    return (isset($docsList['solar_installation_proof'])) ? [$docsList['solar_installation_proof'], true] : false;
                }
                break;
            case 'processing_fee':
                if ($application->emi && $application->emi->processing_fee > 0) {
                    $merchant = Merchant::where('id', $application->merchant_id)->first(['is_collected']);
                    $processing_fee_status = '<span style="font-size:12px;">Processing fee will be receive from merchant</span>';
                    if (isset($merchant->is_collected)) {
                        $proFormaInvoice = ProFormaInvoice::where('application_id', $application->id)->first(['processing_fee_by_merchant']);
                        if (($proFormaInvoice && is_null($proFormaInvoice->processing_fee_by_merchant) && $merchant->is_collected == 0) || (isset($proFormaInvoice->processing_fee_by_merchant) && $proFormaInvoice->processing_fee_by_merchant == 0)) {
                            if (isset($docsList['processing_fee_receipt'])) {
                                $processing_fee_status = '<span style="font-size:12px;"><a class="btn btn-primary col-md-12" href="/admin/consumer-application/get-documents/'.$docsList['processing_fee_receipt'].'" target="_blank">View Details</a></span>'; //Processing fee received from customer
                            } else if ((isset($_GET['state']) && $_GET['state'] == 'disbursement checklist done') || (!isset($_GET['state']) && $application->state != 'waiting for documents')) {
                                $accountingController = new AccountingController();
                                $processingDue = $accountingController->getApplicationDueAmount($application->id);
                                if ($processingDue['processing_fee_due'] > 0) {
                                    $t = "'Processing fee not received from customer'";
                                    $isRequired = '';
                                    $offer = MerchantOffers::where('id', $application->emi->offer_id)->first(['processing_fee_first_emi']);
                                    if (in_array('disbursement checklist done', $pastLogs)) {
                                        $isRequired = 'required="required"';
                                    }

                                    $isRequiredProcessingFee = 'required="required"';

                                    if(isset($offer->processing_fee_first_emi) && $offer->processing_fee_first_emi) {
                                        $processing_fee_status = '<span style="font-size:12px;">Processing Fees will be collected with 1st EMI</span>';
                                    }else{
                                        $processing_fee_status = '<i class="fa fa-exclamation-triangle" aria-hidden="true" style="margin-right: 6px;color: red;" title="Processing fee not received from customer"></i><input type="text" style="width: 0;height: 0;position: absolute;border: 0;outline: none;" oninvalid="this.setCustomValidity(' . $t . ')" name="pros" ' . $isRequired . ' '.$isRequiredProcessingFee.'/><span style="font-size:12px;color:red">Processing fee of Rs. ' . $processingDue['processing_fee_due'] . ' is pending from customer</span>';
                                    }
                                } else {
                                    $processing_fee_status = '<span style="font-size:12px;"><a href="javascript:void(0);" class="btn btn-primary col-md-12" data-toggle="modal" data-target="#viewProcessingFee">View Details</a></span>'; //Processing fee received from customer
                                }
                            }
                        }
                    }
                } else {
                    $processing_fee_status = '<span style="font-size:12px;">Processing fee is 0</span>';

                }
                return [$processing_fee_status, true];
                break;

        }
    }

    public function getProcessingFeeData($id){

        $paymentTransactions = PaymentTransaction::with('paidBy')->where('application_id', $id)->where('payment_for','processing_fee')->whereNull('deleted_by')->whereNull('refunded_by')->get();
        $application = ConsumerApplication::where('id', $id)->first(['id','name']);
        $data = [];

        foreach ($paymentTransactions as $paymentTransaction) {

            $data[] =  [
                'amount' => $paymentTransaction->amount,
                'mode' => $paymentTransaction->mode,
                'transaction_id' => $paymentTransaction->trasanction_id,
                'transaction_date' => $paymentTransaction->payment_date,
                'paid_by' => $paymentTransaction->paidBy->name ?? $application->name,
                'transaction_status' => $paymentTransaction->status,
                'acknowledgment_receipt' => $paymentTransaction->trasanction_acknowledgement,
                'wallet_name' => $paymentTransaction->wallet_name,
                'payment_for' => 'Processing Fee',
            ];
        }
        return $data;
    }


    public function getNewVerificationList()
    {
        return [
            ['key' => 'residing', 'name' => 'Residing in negative area', 'status' => false, 'value' => '', 'radio' => 1, 'group' => 'Personal Verified', 'fixed' => 1],
            ['key' => 'pan_validation', 'name' => 'Pan Validation', 'status' => false, 'link' => 1, 'value' => '', 'else' => 'file', 'group' => 'Personal Verified'],
            ['key' => 'negative_area', 'name' => 'Negative Area', 'status' => true, 'link' => 1, 'value' => '', 'else' => 'file', 'group' => 'Personal Verified'],
            ['key' => 'linkedin', 'placeholder' => 'Paste the link here in box', 'name' => 'Seen in Linkedin', 'status' => false, 'value' => '', 'input' => 1, 'else' => 'text', 'group' => 'Personal Verified'],
            ['key' => 'facebook', 'placeholder' => 'Paste the link here in box', 'name' => 'Seen in Facebook', 'status' => false, 'value' => '', 'input' => 1, 'else' => 'text', 'group' => 'Personal Verified'],
            ['key' => 'negative_profession', 'name' => 'Negative Profession', 'status' => false, 'value' => '', 'radio' => 1, 'group' => 'Personal Verified', 'view' => ['Acceptable' => false, 'Reason' => '', 'isMandatory' => false], 'fixed' => 1],
            ['key' => 'blood_relative', 'name' => 'Blood Relative (Co-Applicant)', 'status' => false, 'value' => '', 'radio' => 1, 'group' => 'Personal Verified', 'view' => ['Acceptable' => false, 'Reason' => '', 'isMandatory' => false]],
            ['key' => 'reference_taken', 'name' => 'Reference Taken', 'status' => false, 'value' => '', 'radio' => 1, 'group' => 'Personal Verified'],
            //['key' => 'utility_bill_verified', 'name' => 'Utility Bill Verified', 'status' => false, 'value' => '', 'radio' => 1, 'group' => 'Personal Verified'],
            ['key' => 'loan_term', 'name' => 'Loan Term', 'status' => true, 'value' => 0, 'group' => 'Loan Details', 'view' => ['Acceptable' => false, 'Reason' => '', 'isMandatory' => false], 'fixed' => 1],
            ['key' => 'monthly_income', 'name' => 'Monthly Income', 'status' => true, 'value' => 0, 'group' => 'Loan Details', 'view' => ['Acceptable' => false, 'Reason' => '', 'isMandatory' => false], 'fixed' => 1],
            ['key' => 'income_proof', 'name' => 'Income Proof', 'status' => true, 'value' => 0, 'group' => 'Loan Details', 'view' => ['Acceptable' => false, 'Reason' => '', 'isMandatory' => false], 'fixed' => 1],
            ['key' => 'loan_amount', 'name' => 'Loan Amount', 'status' => true, 'value' => 0, 'group' => 'Loan Details', 'view' => ['Acceptable' => false, 'Reason' => '', 'isMandatory' => false], 'fixed' => 1],
            ['key' => 'foir', 'name' => 'FOIR', 'status' => true, 'value' => 0, 'group' => 'Loan Details', 'view' => ['Acceptable' => false, 'Reason' => '', 'isMandatory' => false], 'fixed' => 1],
            ['key' => 'applicant_age', 'name' => 'Customer Age', 'status' => true, 'value' => 0, 'group' => 'Personal Verified', 'view' => ['Acceptable' => false, 'Reason' => '', 'isMandatory' => false], 'fixed' => 1],

//            ['key' => 'product_details', 'name' => 'Product Details', 'status' => true, 'link' => 1, 'value' => '', 'group' => 'Product Verified', 'fixed' => 1],
//            ['key' => 'product_verification', 'name' => 'Loan Amount < Product Amount', 'status' => true, 'value' => '', 'radio' => 1, 'view' => ['Acceptable' => false, 'Reason' => '', 'isMandatory' => false], 'group' => 'Product Verified', 'fixed' => 1],

            ['key' => 'pan_card', 'name' => 'Pan Card', 'status' => false, 'value' => '', 'radio' => 1, 'group' => 'Applicant\'s Credit report (EQUIFAX) verified', 'fixed' => 1],
            ['key' => 'aadhar_front', 'name' => 'Aaadhar Front', 'status' => false, 'value' => '', 'radio' => 1, 'group' => 'Applicant\'s Credit report (EQUIFAX) verified', 'fixed' => 1],
            ['key' => 'aadhar_back', 'name' => 'Aaadhar Back', 'status' => false, 'value' => '', 'radio' => 1, 'group' => 'Applicant\'s Credit report (EQUIFAX) verified', 'fixed' => 1],
            ['key' => 'selfie', 'name' => 'Selfie', 'status' => false, 'value' => '', 'radio' => 1, 'group' => 'Applicant\'s Credit report (EQUIFAX) verified', 'fixed' => 1],
            ['key' => 'date_of_birth', 'name' => 'Date of Birth', 'status' => false, 'value' => '', 'radio' => 1, 'group' => 'Applicant\'s Credit report (EQUIFAX) verified', 'fixed' => 1],
            ['key' => 'dpd', 'name' => 'DPD in active loan or credit card from last 6 months', 'status' => true, 'value' => 0, 'group' => 'Applicant\'s Credit report (EQUIFAX) verified', 'view' => ['Acceptable' => false, 'Reason' => '', 'isMandatory' => false], 'fixed' => 1],
            ['key' => 'writeen_settled_suit', 'name' => 'Is there any Written Off,Settled,Suit filed etc such negative status in recent two years', 'status' => false, 'value' => '', 'radio' => 1, 'group' => 'Applicant\'s Credit report (EQUIFAX) verified', 'view' => ['Acceptable' => false, 'Reason' => '', 'isMandatory' => false]],
            ['key' => 'enquiries', 'name' => 'Several enquiries in the past 12 months (more than 5)', 'status' => true, 'value' => 0, 'else' => 'div', 'div' => 1, 'group' => 'Applicant\'s Credit report (EQUIFAX) verified', 'fixed' => 1],
            ['key' => 'credit_score', 'name' => 'Credit Score', 'status' => true, 'value' => 0, 'group' => 'Applicant\'s Credit report (EQUIFAX) verified', 'view' => ['Acceptable' => false, 'Reason' => '', 'isMandatory' => false],'fixed' => 1],
            ['key' => 'pl_gl_taken', 'name' => 'Personal Loan/Gold Loan Recently taken', 'status' => false, 'value' => '', 'radio' => 1, 'group' => 'Applicant\'s Credit report (EQUIFAX) verified','fixed' => 1],


            ['key' => 'mca', 'name' => 'MCA', 'status' => false, 'type' => 'file', 'link' => 1, 'value' => '', 'else' => 'file', 'group' => 'Applicant\'s Occupation profile verified'],
            ['key' => 'prode', 'name' => 'Probe42', 'status' => false, 'type' => 'file', 'link' => 1, 'value' => '', 'else' => 'file', 'group' => 'Applicant\'s Occupation profile verified'],
            ['key' => 'joining_date', 'name' => 'Joining date', 'status' => false, 'value' => '', 'input' => 1, 'else' => 'text', 'group' => 'Applicant\'s Occupation profile verified'],
            ['key' => 'designation', 'name' => 'Designation', 'status' => false, 'value' => '', 'input' => 1, 'else' => 'text', 'group' => 'Applicant\'s Occupation profile verified'],
            ['key' => 'verify_pro_crt', 'name' => 'Verify professional certificates', 'status' => false, 'value' => '', 'radio' => 1, 'group' => 'Applicant\'s Occupation profile verified'],
            ['key' => 'official_email', 'name' => 'Official email ID', 'status' => false, 'value' => '', 'input' => 1, 'else' => 'text', 'group' => 'Applicant\'s Occupation profile verified'],
            ['key' => 'office_address', 'name' => 'Office Address', 'status' => false, 'value' => '', 'modal' => '#office_address_element', 'group' => 'Applicant\'s Occupation profile verified'],
            ['key' => 'epf_uan', 'name' => 'EPF UAN Lookup', 'status' => true, 'value' => '', 'link' => 1, 'group' => 'Applicant\'s Occupation profile verified'],
            ['key' => 'work_experience', 'name' => 'Work Experience', 'status' => true, 'value' => 0, 'group' => 'Applicant\'s Occupation profile verified', 'view' => ['Acceptable' => false, 'Reason' => '', 'isMandatory' => false]],

            ['key' => 'utility_bill_validated', 'name' => 'Utility Bill Validated', 'status' => false, 'value' => '', 'radio' => 1, 'group' => 'Applicant\'s Residence verified'],
            ['key' => 'cpv_ic', 'name' => 'CPV Initiated/Conducted', 'status' => false, 'value' => '', 'radio' => 1, 'group' => 'Applicant\'s Residence verified'],

            ['key' => 'salary', 'name' => 'Salary are reflecting in bank statement', 'status' => false, 'value' => '', 'radio' => 1, 'group' => 'Applicant\'s Banking verified', 'view' => ['Acceptable' => false, 'Reason' => '', 'isMandatory' => false]],
            ['key' => 'regular_high_value', 'name' => 'Any regular high value monthly transactions (Debit or credit)', 'status' => false, 'value' => '', 'radio' => 1, 'group' => 'Applicant\'s Banking verified'],
            ['key' => 'bank_statement_file', 'name' => 'Bank Statement', 'status' => true, 'value' => 0, 'group' => 'Applicant\'s Banking verified', 'view' => ['Acceptable' => false, 'Reason' => '', 'isMandatory' => false]],
            ['key' => 'out_cb_eb', 'name' => 'Outward Cheque Bounces/ECS Bounces', 'status' => false, 'value' => '', 'radio' => 1, 'group' => 'Applicant\'s Banking verified', 'view' => ['Acceptable' => false, 'Reason' => '', 'isMandatory' => false]],
            ['key' => 'abb_emi', 'name' => 'Average Bank Balance (ABB)/EMI', 'status' => true, 'value' => 0, 'group' => 'Applicant\'s Banking verified', 'view' => ['Acceptable' => false, 'Reason' => '', 'isMandatory' => false]],
            ['key' => 'in_cb', 'name' => 'Inward Cheque Bounces', 'status' => false, 'value' => '', 'radio' => 1, 'group' => 'Applicant\'s Banking verified'],
            ['key' => 'min_balance_charge', 'name' => 'Minimum Balance Charges', 'status' => false, 'value' => '', 'radio' => 1, 'group' => 'Applicant\'s Banking verified', 'view' => ['Acceptable' => false, 'Reason' => '', 'isMandatory' => false]],
            ['key' => 'suspicious_file_input', 'name' => 'Suspicious File Input', 'status' => false, 'value' => '', 'radio' => 1, 'group' => 'Applicant\'s Banking verified', 'view' => ['Acceptable' => false, 'Reason' => '', 'isMandatory' => false], 'fixed' => 1],

        ];
    }

    public function getVerificationListV1()
    {
        $statusArray = [
            ['key' => 'residing', 'name' => 'Residing in negative area', 'status' => false, 'value' => '', 'radio' => 1, 'group' => 'Personal Verified', 'fixed' => 1],
            ['key' => 'negative_profile', 'name' => 'Check Negative Profession', 'status' => false, 'modal' => '#negative_profile', 'value' => '', 'group' => 'Personal Verified'],
            ['key' => 'pan_validation', 'name' => 'Pan Validation', 'status' => false, 'link' => 1, 'value' => '', 'else' => 'file', 'group' => 'Personal Verified'],
            // ['key' => 'bank_validation', 'name' => 'Bank Validation', 'status' => true, 'link' => 1, 'value' => '', 'else' => 'file', 'group' => 'Personal Verified'],
            ['key' => 'negative_area', 'name' => 'Negative Area', 'status' => true, 'link' => 1, 'value' => '', 'else' => 'file', 'group' => 'Personal Verified'],
            ['key' => 'courier', 'name' => 'Courier', 'status' => true, 'link' => 1, 'value' => '', 'else' => 'file', 'group' => 'Personal Verified'],
            ['key' => 'customer_age', 'name' => 'Customer Age (20 to 65 years)', 'status' => false, 'input' => 1, 'value' => '', 'group' => 'Personal Verified'],
            ['key' => 'linkedin', 'placeholder' => 'Paste the link here in box', 'name' => 'Seen in Linkedin', 'status' => false, 'value' => '', 'input' => 1, 'else' => 'text', 'group' => 'Personal Verified'],
            ['key' => 'facebook', 'placeholder' => 'Paste the link here in box', 'name' => 'Seen in Facebook', 'status' => false, 'value' => '', 'input' => 1, 'else' => 'text', 'group' => 'Personal Verified'],
            ['key' => 'tele_verification', 'name' => 'Tele verification', 'status' => false, 'value' => '', 'radio' => 1, 'group' => 'Personal Verified'],

            ['key' => 'product_details', 'name' => 'Product Details', 'status' => true, 'link' => 1, 'value' => '', 'group' => 'Product Verified', 'fixed' => 1],
            ['key' => 'product_verification', 'name' => 'Loan Amount < Product Amount', 'status' => true, 'value' => '', 'radio' => 1, 'view' => ['Acceptable' => false, 'Reason' => '', 'isMandatory' => false], 'group' => 'Product Verified', 'fixed' => 1],

            //['key' => 'credit_score', 'name' => 'Credit score is more than 625', 'status' => false, 'value' => '', 'div' => 1, 'group' => 'Applicant\'s Credit report (EQUIFAX) verified', 'fixed' => 1],
            //['key' => 'pan_card', 'name' => 'Pan Card', 'status' => false, 'value' => '', 'radio' => 1, 'group' => 'Applicant\'s Credit report (EQUIFAX) verified', 'fixed' => 1],
            //['key' => 'aadhar', 'name' => 'Aaadhar', 'status' => false, 'value' => '', 'radio' => 1, 'group' => 'Applicant\'s Credit report (EQUIFAX) verified', 'fixed' => 1],
            //['key' => 'date_of_birth', 'name' => 'Date of Birth', 'status' => false, 'value' => '', 'radio' => 1, 'group' => 'Applicant\'s Credit report (EQUIFAX) verified', 'fixed' => 1],
            //['key' => 'dpd', 'name' => 'DPD in active loan or credit card from last 6 months', 'status' => true, 'value' => 0, 'div' => 1, 'else' => 'div', 'group' => 'Applicant\'s Credit report (EQUIFAX) verified', 'fixed' => 1],
            //['key' => 'writeen_settled_suit', 'name' => 'Is there any Written Off,Settled,Suit filed etc such negative status in recent two years', 'status' => false, 'value' => '', 'radio' => 1, 'group' => 'Applicant\'s Credit report (EQUIFAX) verified', 'fixed' => 1],
            //['key' => 'enquiries', 'name' => 'Several enquiries in the past 12 months (more than 5)', 'status' => true, 'value' => 0, 'else' => 'div', 'div' => 1, 'group' => 'Applicant\'s Credit report (EQUIFAX) verified', 'fixed' => 1],
            //['key' => 'salary', 'name' => 'Salary are reflecting in bank statement', 'status' => false, 'value' => '', 'radio' => 1, 'group' => 'Applicant\'s Banking verified'],
            //['key' => 'no_debit_chq_bounce_ecs', 'name' => 'No Debit balance,Chq Bounces, ECS Bounces', 'status' => false, 'value' => '', 'radio' => 1, 'group' => 'Applicant\'s Banking verified'],
            //['key' => 'regular_high_value', 'name' => 'Any regular high value monthly transactions (Debit or credit)', 'status' => false, 'value' => '', 'radio' => 1, 'group' => 'Applicant\'s Banking verified'],
            //['key' => 'average_balance', 'name' => 'Average Balance (Minimum Rs. 25,000)', 'status' => false, 'value' => '', 'radio' => 1, 'group' => 'Applicant\'s Banking verified'],
            //['key' => 'mca', 'name' => 'MCA', 'status' => false, 'type' => 'file', 'link' => 1, 'value' => '', 'else' => 'file', 'group' => 'Applicant\'s Occupation profile verified'],
            //['key' => 'prode', 'name' => 'Probe42', 'status' => false, 'type' => 'file', 'link' => 1, 'value' => '', 'else' => 'file', 'group' => 'Applicant\'s Occupation profile verified'],
            //['key' => 'joining_date', 'name' => 'Joining date', 'status' => false, 'value' => '', 'input' => 1, 'else' => 'text', 'group' => 'Applicant\'s Occupation profile verified'],
            //['key' => 'designation', 'name' => 'Designation', 'status' => false, 'value' => '', 'input' => 1, 'else' => 'text', 'group' => 'Applicant\'s Occupation profile verified'],
            //['key' => 'verify_pro_crt', 'name' => 'Verify professional certificates', 'status' => false, 'value' => '', 'radio' => 1, 'group' => 'Applicant\'s Occupation profile verified'],
            //['key' => 'official_email', 'name' => 'Official email ID', 'status' => false, 'value' => '', 'input' => 1, 'else' => 'text', 'group' => 'Applicant\'s Occupation profile verified'],
            //['key' => 'office_address', 'name' => 'Office Address', 'status' => false, 'value' => '', 'modal' => '#office_address_element', 'group' => 'Applicant\'s Occupation profile verified'],
            //['key' => 'epf_uan', 'name' => 'EPF UAN Lookup', 'status' => true, 'value' => '', 'link' => 1, 'group' => 'Applicant\'s Occupation profile verified'],
            //['key' => 'utility_bill', 'name' => 'Utilities bill online', 'status' => false, 'link' => 1, 'value' => '', 'else' => 'file', 'group' => 'Applicant\'s Residence verified'],
            //['key' => 'cpv', 'name' => 'Conduct CPV of residence', 'status' => false, 'link' => 1, 'value' => '', 'else' => 'file', 'data-attr' => 'multiple', 'group' => 'Applicant\'s Residence verified', 'required' => false],
            ['key' => 'nach', 'name' => 'Complete signed NACH form', 'status' => false, 'link' => 1, 'value' => '', 'else' => 'file', 'group' => 'disbursement checklist done'],
            ['key' => 'signed_loan_agreement', 'name' => 'Signed Loan Agreement', 'status' => false, 'link' => 1, 'value' => '', 'else' => 'file', 'group' => 'disbursement checklist done'],
            ['key' => 'cheques', 'name' => 'Undated or post dated Cheques', 'status' => false, 'link' => 1, 'value' => '', 'else' => 'file', 'group' => 'disbursement checklist done'],
            ['key' => 'advance_payment', 'name' => 'Advance payment confirmation', 'status' => false, 'link' => 1, 'value' => '', 'else' => 'file', 'group' => 'disbursement checklist done'],
            ['key' => 'proform', 'name' => 'Final quotation bill or signed proforma invoice from merchant', 'status' => false, 'link' => 1, 'value' => '', 'else' => 'file', 'group' => 'Product Verified'],
            // ['key' => 'solar_installation_proof', 'name' => 'Solar Installation proofs', 'status' => false, 'link' => 1, 'value' => '', 'else' => 'file', 'group' => 'Product Verified'],

            ['key' => 'processing_fee', 'name' => 'Processing Fee Received', 'status' => false, 'div' => 1, 'value' => '', 'else' => 'div', 'group' => 'disbursement checklist done'],
            ['key' => 'designation', 'name' => 'Designation', 'status' => false, 'div' => 1, 'value' => '', 'else' => 'text', 'group' => 'Personal Verified', 'required' => false],
            ['key' => 'department', 'name' => 'Department', 'status' => false, 'div' => 1, 'value' => '', 'else' => 'text', 'group' => 'Personal Verified', 'required' => false],
            ['key' => 'contact', 'name' => 'Contact', 'status' => false, 'div' => 1, 'value' => '', 'else' => 'text', 'group' => 'Personal Verified', 'required' => false],
            ['key' => 'product_name', 'name' => 'Product Name', 'status' => false, 'div' => 1, 'value' => '', 'else' => 'text', 'group' => 'Product Verified', 'required' => true],
            ['key' => 'call_recording', 'name' => 'Call Recording', 'status' => false, 'div' => 1, 'value' => '', 'modal' => '#call_recording_modal', 'else' => 'file', 'group' => 'disbursement checklist done', 'required' => false],
            //['key' => 'self_attested', 'name' => 'Self Attested', 'status' => false, 'link' => 1, 'value' => '', 'else' => 'file', 'group' => 'disbursement checklist done', 'required' => true],
            //['key' => 'original_seen_verified', 'name' => 'Original Seen Verified', 'status' => false, 'link' => 1, 'value' => '', 'else' => 'file', 'group' => 'disbursement checklist done', 'required' => false],
            ['key' => 'credit_appraisal_memo', 'name' => 'Credit Appraisal Memo', 'status' => false, 'link' => 1, 'value' => '', 'else' => 'file', 'group' => 'disbursement checklist done', 'required' => false],
            ['key' => 'sanction_letter', 'name' => 'Sanction Letter', 'status' => false, 'link' => 1, 'value' => '', 'else' => 'file', 'group' => 'disbursement checklist done', 'required' => false],

            ['key' => 'digio_kyc', 'name' => 'Digio KYC', 'status' => false, 'div' => 1, 'value' => '', 'modal' => '#digio_kyc', 'else' => 'div', 'group' => 'KYC Details', 'required' => true],
            // ['key' => 'onfido_kyc', 'name' => 'Onfido KYC', 'status' => false, 'div' => 1, 'value' => '', 'else' => 'div', 'group' => 'KYC Details', 'required' => true],
            ['key' => 'co_app_digio_kyc', 'name' => 'Co-Applicant\'s Digio KYC', 'status' => false, 'div' => 1, 'value' => '', 'modal' => '#co_app_digio_kyc', 'else' => 'div', 'group' => 'Co-Applicant KYC Details', 'required' => true],
            ['key' => 'co_app_onfido_kyc', 'name' => 'Co-Applicant\'s Onfido KYC', 'status' => false, 'div' => 1, 'value' => '', 'else' => 'div', 'group' => 'Co-Applicant KYC Details', 'required' => true],

            ['key' => 'mandate_status', 'name' => 'Mandate Status', 'status' => false, 'div' => 1, 'value' => '', 'system_value' => '', 'group' => 'Bank & Mandate Verification Checklist', 'required' => true],
            ['key' => 'mandate_amount', 'name' => 'Mandate Amount', 'status' => false, 'div' => 1, 'value' => '', 'system_value' => '', 'group' => 'Bank & Mandate Verification Checklist', 'required' => true],
            ['key' => 'mandate_amount_exception_remarks', 'name' => 'Exception Remarks', 'status' => false, 'div' => 1, 'value' => '', 'system_value' => '', 'else' => 'text', 'input' => 1, 'group' => 'Bank & Mandate Verification Checklist', 'required' => false],
            ['key' => 'mandate_misc_collection_date', 'name' => 'Lender Collection Date', 'status' => false, 'div' => 1, 'value' => '', 'system_value' => '', 'group' => 'Bank & Mandate Verification Checklist', 'required' => true],
            ['key' => 'mandate_misc_emi_day', 'name' => 'Lender EMI Day', 'status' => false, 'div' => 1, 'value' => '', 'system_value' => '', 'group' => 'Bank & Mandate Verification Checklist', 'required' => true],
            ['key' => 'mandate_document', 'name' => 'Mandate Document', 'status' => false, 'link' => 1, 'value' => '', 'system_value' => '', 'else' => 'file', 'group' => 'Bank & Mandate Verification Checklist', 'required' => false],
            ['key' => 'mandate_utility_code', 'name' => 'Utility Code', 'status' => false, 'div' => 1, 'value' => '', 'system_value' => '', 'group' => 'Bank & Mandate Verification Checklist', 'required' => false],
            ['key' => 'mandate_creditor_name', 'name' => 'Creditor Name', 'status' => false, 'div' => 1, 'value' => '', 'system_value' => '', 'group' => 'Bank & Mandate Verification Checklist', 'required' => false],
            ['key' => 'mandate_last_emi_date', 'name' => 'Last EMI Date', 'status' => false, 'div' => 1, 'value' => '', 'system_value' => '', 'group' => 'Bank & Mandate Verification Checklist', 'required' => false],
            ['key' => 'mandate_document_exception_remarks', 'name' => 'Exception Remarks', 'status' => false, 'div' => 1, 'value' => '', 'system_value' => '', 'else' => 'text', 'input' => 1, 'group' => 'Bank & Mandate Verification Checklist', 'required' => false],
            // ['key' => 'bank_details', 'name' => 'Bank Details' , 'status' => false , 'div' => 1, 'value' => '', 'system_value' => '', 'group' => 'Bank & Mandate Verification Checklist', 'required' => false],

        ];

        if (self::VKYC_VENDOR == "karza") {
            $statusArray[] = ['key' => 'hyperverge_kyc', 'name' => 'Karza KYC', 'status' => false, 'div' => 1, 'value' => '', 'modal' => '#hyperverge_kyc', 'else' => 'div', 'group' => 'KYC Details', 'required' => true];
            $statusArray[] = ['key' => 'co_app_hyperverge_kyc', 'name' => 'Co-Applicant\'s Karza KYC', 'status' => false, 'div' => 1, 'value' => '','modal' => '#co_app_hyperverge_kyc', 'else' => 'div', 'group' => 'Co-Applicant KYC Details', 'required' => true];
        }else {
            $statusArray[] = ['key' => 'hyperverge_kyc', 'name' => 'Hyperverge KYC', 'status' => false, 'div' => 1, 'value' => '', 'modal' => '#hyperverge_kyc', 'else' => 'div', 'group' => 'KYC Details', 'required' => true];
            $statusArray[] = ['key' => 'co_app_hyperverge_kyc', 'name' => 'Co-Applicant\'s Hyperverge KYC', 'status' => false, 'div' => 1, 'value' => '','modal' => '#co_app_hyperverge_kyc', 'else' => 'div', 'group' => 'Co-Applicant KYC Details', 'required' => true];
        }
        return $statusArray;
    }

    private function getMultiStageProperties($id, $offer_id, $verifications)
    {

        $multiStageProperties = DisbursementOffersData::where('offer_id', $offer_id)->get(['id','per_disbursement_amount', 'disbursement_at', 'phase']);
        if (isset($multiStageProperties[0]->id)) {
            foreach ($multiStageProperties as $item) {
                array_push($verifications, ['key' => 'phase_id_' . $item->phase, 'name' => 'Disbursement ' . $item->phase . ' Phase', 'status' => true, 'div' => 1, 'value' => ucwords(str_replace('_', ' ',$item->disbursement_at)), 'else' => 'text', 'group' => 'Product Verified']);
                array_push($verifications, ['key' => 'phase_id_' . $item->phase, 'name' => 'Disbursement (%)', 'status' => true, 'div' => 1, 'value' => $item->per_disbursement_amount, 'else' => 'text', 'group' => 'Product Verified']);
            }
        }
        return $verifications;
    }

    public function getVerificationList()
    {
        $statusArray = [
            ['key' => 'residing', 'name' => 'Residing in negative area', 'status' => false, 'value' => '', 'radio' => 1, 'group' => 'Personal Verified', 'fixed' => 1],
            ['key' => 'negative_profile', 'name' => 'Check Negative Profession', 'status' => false, 'modal' => '#negative_profile', 'value' => '', 'group' => 'Personal Verified'],
            ['key' => 'pan_validation', 'name' => 'Pan Validation', 'status' => false, 'link' => 1, 'value' => '', 'else' => 'file', 'group' => 'Personal Verified'],
            ['key' => 'bank_validation', 'name' => 'Bank Validation', 'status' => true, 'link' => 1, 'value' => '', 'else' => 'file', 'group' => 'Personal Verified'],
            ['key' => 'negative_area', 'name' => 'Negative Area', 'status' => true, 'link' => 1, 'value' => '', 'else' => 'file', 'group' => 'Personal Verified'],
            ['key' => 'courier', 'name' => 'Courier', 'status' => true, 'link' => 1, 'value' => '', 'else' => 'file', 'group' => 'Personal Verified'],
            ['key' => 'customer_age', 'name' => 'Customer Age (20 to 65 years)', 'status' => false, 'input' => 1, 'value' => '', 'group' => 'Personal Verified'],
            ['key' => 'linkedin', 'placeholder' => 'Paste the link here in box', 'name' => 'Seen in Linkedin', 'status' => false, 'value' => '', 'input' => 1, 'else' => 'text', 'group' => 'Personal Verified'],
            ['key' => 'facebook', 'placeholder' => 'Paste the link here in box', 'name' => 'Seen in Facebook', 'status' => false, 'value' => '', 'input' => 1, 'else' => 'text', 'group' => 'Personal Verified'],
            ['key' => 'tele_verification', 'name' => 'Tele verification', 'status' => false, 'value' => '', 'radio' => 1, 'group' => 'Personal Verified'],

            ['key' => 'product_details', 'name' => 'Product Details', 'status' => true, 'link' => 1, 'value' => '', 'group' => 'Product Verified', 'fixed' => 1],
            ['key' => 'product_verification', 'name' => 'Loan Amount < Product Amount', 'status' => true, 'value' => '', 'radio' => 1, 'view' => ['Acceptable' => false, 'Reason' => '', 'isMandatory' => false], 'group' => 'Product Verified', 'fixed' => 1],

            //['key' => 'credit_score', 'name' => 'Credit score is more than 625', 'status' => false, 'value' => '', 'div' => 1, 'group' => 'Applicant\'s Credit report (EQUIFAX) verified', 'fixed' => 1],
            //['key' => 'pan_card', 'name' => 'Pan Card', 'status' => false, 'value' => '', 'radio' => 1, 'group' => 'Applicant\'s Credit report (EQUIFAX) verified', 'fixed' => 1],
            //['key' => 'aadhar', 'name' => 'Aaadhar', 'status' => false, 'value' => '', 'radio' => 1, 'group' => 'Applicant\'s Credit report (EQUIFAX) verified', 'fixed' => 1],
            //['key' => 'date_of_birth', 'name' => 'Date of Birth', 'status' => false, 'value' => '', 'radio' => 1, 'group' => 'Applicant\'s Credit report (EQUIFAX) verified', 'fixed' => 1],
            //['key' => 'dpd', 'name' => 'DPD in active loan or credit card from last 6 months', 'status' => true, 'value' => 0, 'div' => 1, 'else' => 'div', 'group' => 'Applicant\'s Credit report (EQUIFAX) verified', 'fixed' => 1],
            //['key' => 'writeen_settled_suit', 'name' => 'Is there any Written Off,Settled,Suit filed etc such negative status in recent two years', 'status' => false, 'value' => '', 'radio' => 1, 'group' => 'Applicant\'s Credit report (EQUIFAX) verified', 'fixed' => 1],
            //['key' => 'enquiries', 'name' => 'Several enquiries in the past 12 months (more than 5)', 'status' => true, 'value' => 0, 'else' => 'div', 'div' => 1, 'group' => 'Applicant\'s Credit report (EQUIFAX) verified', 'fixed' => 1],
            //['key' => 'salary', 'name' => 'Salary are reflecting in bank statement', 'status' => false, 'value' => '', 'radio' => 1, 'group' => 'Applicant\'s Banking verified'],
            //['key' => 'no_debit_chq_bounce_ecs', 'name' => 'No Debit balance,Chq Bounces, ECS Bounces', 'status' => false, 'value' => '', 'radio' => 1, 'group' => 'Applicant\'s Banking verified'],
            //['key' => 'regular_high_value', 'name' => 'Any regular high value monthly transactions (Debit or credit)', 'status' => false, 'value' => '', 'radio' => 1, 'group' => 'Applicant\'s Banking verified'],
            //['key' => 'average_balance', 'name' => 'Average Balance (Minimum Rs. 25,000)', 'status' => false, 'value' => '', 'radio' => 1, 'group' => 'Applicant\'s Banking verified'],
            //['key' => 'mca', 'name' => 'MCA', 'status' => false, 'type' => 'file', 'link' => 1, 'value' => '', 'else' => 'file', 'group' => 'Applicant\'s Occupation profile verified'],
            //['key' => 'prode', 'name' => 'Probe42', 'status' => false, 'type' => 'file', 'link' => 1, 'value' => '', 'else' => 'file', 'group' => 'Applicant\'s Occupation profile verified'],
            //['key' => 'joining_date', 'name' => 'Joining date', 'status' => false, 'value' => '', 'input' => 1, 'else' => 'text', 'group' => 'Applicant\'s Occupation profile verified'],
            //['key' => 'designation', 'name' => 'Designation', 'status' => false, 'value' => '', 'input' => 1, 'else' => 'text', 'group' => 'Applicant\'s Occupation profile verified'],
            //['key' => 'verify_pro_crt', 'name' => 'Verify professional certificates', 'status' => false, 'value' => '', 'radio' => 1, 'group' => 'Applicant\'s Occupation profile verified'],
            //['key' => 'official_email', 'name' => 'Official email ID', 'status' => false, 'value' => '', 'input' => 1, 'else' => 'text', 'group' => 'Applicant\'s Occupation profile verified'],
            //['key' => 'office_address', 'name' => 'Office Address', 'status' => false, 'value' => '', 'modal' => '#office_address_element', 'group' => 'Applicant\'s Occupation profile verified'],
            //['key' => 'epf_uan', 'name' => 'EPF UAN Lookup', 'status' => true, 'value' => '', 'link' => 1, 'group' => 'Applicant\'s Occupation profile verified'],
            //['key' => 'utility_bill', 'name' => 'Utilities bill online', 'status' => false, 'link' => 1, 'value' => '', 'else' => 'file', 'group' => 'Applicant\'s Residence verified'],
            //['key' => 'cpv', 'name' => 'Conduct CPV of residence', 'status' => false, 'link' => 1, 'value' => '', 'else' => 'file', 'data-attr' => 'multiple', 'group' => 'Applicant\'s Residence verified', 'required' => false],
            ['key' => 'nach', 'name' => 'Complete signed NACH form', 'status' => false, 'link' => 1, 'value' => '', 'else' => 'file', 'group' => 'disbursement checklist done'],
            ['key' => 'signed_loan_agreement', 'name' => 'Signed Loan Agreement', 'status' => false, 'link' => 1, 'value' => '', 'else' => 'file', 'group' => 'disbursement checklist done'],
            ['key' => 'cheques', 'name' => 'Undated or post dated Cheques', 'status' => false, 'link' => 1, 'value' => '', 'else' => 'file', 'group' => 'disbursement checklist done'],
            ['key' => 'advance_payment', 'name' => 'Advance payment confirmation', 'status' => false, 'link' => 1, 'value' => '', 'else' => 'file', 'group' => 'disbursement checklist done'],
            ['key' => 'proform', 'name' => 'Final quotation bill or signed proforma invoice from merchant', 'status' => false, 'link' => 1, 'value' => '', 'else' => 'file', 'group' => 'Product Verified'],
            ['key' => 'processing_fee', 'name' => 'Processing Fee Received', 'status' => false, 'div' => 1, 'value' => '', 'else' => 'div', 'group' => 'disbursement checklist done'],
            ['key' => 'designation', 'name' => 'Designation', 'status' => false, 'div' => 1, 'value' => '', 'else' => 'text', 'group' => 'Personal Verified', 'required' => false],
            ['key' => 'department', 'name' => 'Department', 'status' => false, 'div' => 1, 'value' => '', 'else' => 'text', 'group' => 'Personal Verified', 'required' => false],
            ['key' => 'contact', 'name' => 'Contact', 'status' => false, 'div' => 1, 'value' => '', 'else' => 'text', 'group' => 'Personal Verified', 'required' => false],
            ['key' => 'product_name', 'name' => 'Product Name', 'status' => false, 'div' => 1, 'value' => '', 'else' => 'text', 'group' => 'Product Verified', 'required' => true],
            ['key' => 'call_recording', 'name' => 'Call Recording', 'status' => false, 'div' => 1, 'value' => '', 'modal' => '#call_recording_modal', 'else' => 'file', 'group' => 'disbursement checklist done', 'required' => false],
            //['key' => 'self_attested', 'name' => 'Self Attested', 'status' => false, 'link' => 1, 'value' => '', 'else' => 'file', 'group' => 'disbursement checklist done', 'required' => true],
            //['key' => 'original_seen_verified', 'name' => 'Original Seen Verified', 'status' => false, 'link' => 1, 'value' => '', 'else' => 'file', 'group' => 'disbursement checklist done', 'required' => false],
            ['key' => 'credit_appraisal_memo', 'name' => 'Credit Appraisal Memo', 'status' => false, 'link' => 1, 'value' => '', 'else' => 'file', 'group' => 'disbursement checklist done', 'required' => false],
            ['key' => 'sanction_letter', 'name' => 'Sanction Letter', 'status' => false, 'link' => 1, 'value' => '', 'else' => 'file', 'group' => 'disbursement checklist done', 'required' => false],

            ['key' => 'digio_kyc', 'name' => 'Digio KYC', 'status' => false, 'div' => 1, 'value' => '', 'modal' => '#digio_kyc', 'else' => 'div', 'group' => 'KYC Details', 'required' => true],
            // ['key' => 'onfido_kyc', 'name' => 'Onfido KYC', 'status' => false, 'div' => 1, 'value' => '', 'else' => 'div', 'group' => 'KYC Details', 'required' => true],
            ['key' => 'co_app_digio_kyc', 'name' => 'Co-Applicant\'s Digio KYC', 'status' => false, 'div' => 1, 'value' => '', 'modal' => '#co_app_digio_kyc', 'else' => 'div', 'group' => 'Co-Applicant KYC Details', 'required' => true],
            ['key' => 'co_app_onfido_kyc', 'name' => 'Co-Applicant\'s Onfido KYC', 'status' => false, 'div' => 1, 'value' => '', 'else' => 'div', 'group' => 'Co-Applicant KYC Details', 'required' => true],
        ];
        if (self::VKYC_VENDOR == "karza") {
            $statusArray[] = ['key' => 'hyperverge_kyc', 'name' => 'Karza KYC', 'status' => false, 'div' => 1, 'value' => '', 'modal' => '#hyperverge_kyc', 'else' => 'div', 'group' => 'KYC Details', 'required' => true];
            $statusArray[] = ['key' => 'co_app_hyperverge_kyc', 'name' => 'Co-Applicant\'s Karza KYC', 'status' => false, 'div' => 1, 'value' => '','modal' => '#co_app_hyperverge_kyc', 'else' => 'div', 'group' => 'Co-Applicant KYC Details', 'required' => true];
        }else {
            $statusArray[] = ['key' => 'hyperverge_kyc', 'name' => 'Hyperverge KYC', 'status' => false, 'div' => 1, 'value' => '', 'modal' => '#hyperverge_kyc', 'else' => 'div', 'group' => 'KYC Details', 'required' => true];
            $statusArray[] = ['key' => 'co_app_hyperverge_kyc', 'name' => 'Co-Applicant\'s Hyperverge KYC', 'status' => false, 'div' => 1, 'value' => '','modal' => '#co_app_hyperverge_kyc', 'else' => 'div', 'group' => 'Co-Applicant KYC Details', 'required' => true];
        }
        return $statusArray;
    }

    public function getBNPLVerificationList()
    {
        return [
            ['key' => 'pan_validation', 'name' => 'Pan Validation', 'status' => false, 'link' => 1, 'value' => '', 'else' => 'file', 'group' => 'Personal Verified'],
            ['key' => 'bank_validation', 'name' => 'Bank Validation', 'status' => true, 'link' => 1, 'value' => '', 'else' => 'file', 'group' => 'Personal Verified'],
            ['key' => 'nach', 'name' => 'Complete signed NACH form', 'status' => false, 'link' => 1, 'value' => '', 'else' => 'file', 'group' => 'disbursement checklist done'],
            ['key' => 'signed_loan_agreement', 'name' => 'Signed Loan Agreement, Undated or post dated Chqeues', 'status' => false, 'link' => 1, 'value' => '', 'else' => 'file', 'group' => 'disbursement checklist done'],
            ['key' => 'proform', 'name' => 'Final quotation bill or signed proforma invoice from merchant', 'status' => false, 'link' => 1, 'value' => '', 'else' => 'file', 'group' => 'Product Verified'],
            ['key' => 'processing_fee', 'name' => 'Processing Fee Received', 'status' => false, 'div' => 1, 'value' => '', 'else' => 'div', 'group' => 'disbursement checklist done'],
        ];
    }

    public function getBNPLVerificationListV1()
    {
        return [
            ['key' => 'pan_validation', 'name' => 'Pan Validation', 'status' => false, 'link' => 1, 'value' => '', 'else' => 'file', 'group' => 'Personal Verified'],
            // ['key' => 'bank_validation', 'name' => 'Bank Validation', 'status' => true, 'link' => 1, 'value' => '', 'else' => 'file', 'group' => 'Personal Verified'],
            ['key' => 'nach', 'name' => 'Complete signed NACH form', 'status' => false, 'link' => 1, 'value' => '', 'else' => 'file', 'group' => 'disbursement checklist done'],
            ['key' => 'signed_loan_agreement', 'name' => 'Signed Loan Agreement, Undated or post dated Chqeues', 'status' => false, 'link' => 1, 'value' => '', 'else' => 'file', 'group' => 'disbursement checklist done'],
            ['key' => 'proform', 'name' => 'Final quotation bill or signed proforma invoice from merchant', 'status' => false, 'link' => 1, 'value' => '', 'else' => 'file', 'group' => 'Product Verified'],
            ['key' => 'processing_fee', 'name' => 'Processing Fee Received', 'status' => false, 'div' => 1, 'value' => '', 'else' => 'div', 'group' => 'disbursement checklist done'],
        ];
    }

    public function checkValidations(Request $request)
    {
        $checks = $request->get('check');
        $data = $request->get('data');
        $id = isset($data['application']) && isset($data['application']->id) ? $data['application']->id : $data['application_id'];
        $application = $data['application'] ?? [];
        $status = $data['status'] ?? '';

        if (!$application) {
            ConsumerApplication::$isCFFoirNotInclude = false;
            $application = ConsumerApplication::with('documents', 'application_element', 'creditReport', 'foir', 'emi', 'mandate', 'checkmandate','merchant','lender_bank','lender','activeOffer', 'payment_transaction', 'proFormaInvoice')->find($id);
        }

        if(in_array($status, ['approved','disbursement checklist done','disbursement query','ready for disbursement']) && $application->lender_id != 2){
            $productStatus = true;
            if(!isset($application->activeOffer)){
                return response(['main' => ['special_notes' => false], 'data' => 'Special Notes For Team <br/><br/> <b> [Error: Incorrect Product Type Selected For '.$application->lender->name.'] </b>', 'hide' => 'special_notes'], 200);
            }
            if(isset($application->lender->product_type_details)){
                $applicantMerchant = $application->merchant;
                $applicantOffer = $application->activeOffer;
                $lenderProductType = json_decode($application->lender->product_type_details);

                if(!empty($lenderProductType->advance_type) && !in_array($applicantOffer->advance_type,$lenderProductType->advance_type)){
                    $productStatus = false;
                }
                if(!empty($lenderProductType->subvention_type) && !in_array($applicantOffer->subvention_type_id,$lenderProductType->subvention_type)){
                    $productStatus = false;
                }
                if(!empty($lenderProductType->disbursement_phase) && !in_array($applicantOffer->disbursement_method,$lenderProductType->disbursement_phase)){
                    $productStatus = false;
                }
                if(!empty($lenderProductType->rate_of_interest) && !in_array($applicantOffer->interest_type_id,$lenderProductType->rate_of_interest)){
                    $productStatus = false;
                }
                if(isset($lenderProductType->gst_applicable) && $applicantMerchant->is_gst == 1 && $applicantMerchant->is_gst != $lenderProductType->gst_applicable){
                    $productStatus = false;
                }
                if(isset($lenderProductType->gst_not_applicable_on_subvention) && $applicantMerchant->is_gst == 0 && $applicantMerchant->is_gst != $lenderProductType->gst_not_applicable_on_subvention){
                    $productStatus = false;
                }
                if(isset($lenderProductType->trade_advance) && $applicantMerchant->is_trade_advance != $lenderProductType->trade_advance){
                    $productStatus = false;
                }
                if(isset($lenderProductType->active_fldg) && $applicantMerchant->is_fldg_active != $lenderProductType->active_fldg){
                    $productStatus = false;
                }
                if(isset($lenderProductType->hold_merchant_liablility) && $applicantMerchant->hold_liability != $lenderProductType->hold_merchant_liablility){
                    $productStatus = false;
                }
                if(isset($lenderProductType->insurance_premium) && $applicantMerchant->insurance_premium != $lenderProductType->insurance_premium){
                    $productStatus = false;
                }
                if(isset($lenderProductType->processing_fees)){
                    if(!(in_array('collected_by_creditfair',$lenderProductType->processing_fees) && in_array('collected_by_merchant',$lenderProductType->processing_fees))){
                        if(in_array('collected_by_creditfair',$lenderProductType->processing_fees) && $applicantMerchant->is_collected != 0){
                            $productStatus = false;
                        }
                        if(in_array('collected_by_merchant',$lenderProductType->processing_fees) && $applicantMerchant->is_collected != 1){
                            $productStatus = false;
                        }
                    }
                    if(in_array('collected_in_first_emi',$lenderProductType->processing_fees) && $applicantOffer->processing_fee_first_emi != 1){
                        $productStatus = false;
                    }
                }
            }
            if(!$productStatus){
                return response(['main' => ['special_notes' => false], 'data' => 'Special Notes For Team <br/><br/> <b> [Error: Incorrect Product Type Selected For '.$application->lender->name.'] </b>', 'hide' => 'special_notes'], 200);
            }
        }
        if ($status == 'approved' && ($this->checkCoAppRequire($application->id)) && $application->application_element->type_of_customer != 4) {
            return response()->json(['co_app_required'=>false], 200);
        }

        if ($status == 'approved' && !isset($data['hide_next'])) {
            $consumerApplication = ConsumerApplication::with('merchant')->where('id', $id)->first(['id', 'merchant_id','approved_amount']);
            if (isset($consumerApplication->merchant) && !empty($consumerApplication->merchant->special_notes)) {
                $prev_app_status = ContentLogger::where('application_id', $id)->where('status','approved')->count();
                if($prev_app_status < 1) {
                    $total = DB::table('consumer_application')->select(DB::raw('count(*) as app_count'), DB::raw('SUM(approved_amount) as total_approved_amount'))->where('merchant_id', $consumerApplication->merchant_id)->whereIn('state', ['approved', 'disbursement checklist done','ready for disbursement','disbursed','nach registered','closed'])->first();
                    $total_remaining_amount = $consumerApplication->merchant->max_approval_value - $total->total_approved_amount;
                    if ($consumerApplication->merchant->status == 'active' && $consumerApplication->merchant->pre_status == 1 && ($consumerApplication->approved_amount > $total_remaining_amount || $total->total_approved_amount > $consumerApplication->merchant->max_approval_value || $total->app_count >= $consumerApplication->merchant->max_no_cases)) {
                        (new \App\Slack(new Request(['title' => 'Approval has been stopped', 'fields' => ['Message' => "Approval has been stopped because the approval limit is reached and " . $consumerApplication->merchant->merchant_name . " status is 'Active for Login'"], 'group' => 'Bd_sales_mgrs'])))->send();
                        return response(['main' => ['merchant_status' => false], 'data' => '<p style="word-break: break-word;">Total value of approved cases or total no. of approved cases is higher than the mentioned limit. Please increase the limit and then try to change the Status</p>'], 200);
                    }
                }
                return response(['main' => ['special_notes' => false], 'data' => 'Special Notes For Credit Team <br/><br/> <b>' . $consumerApplication->merchant->special_notes . '</b>', 'hide' => 'special_notes'], 200);
            }

        }

        if($status == "approved"){
            $consumerApplication = ConsumerApplication::with('merchant')->where('id', $id)->first(['id', 'merchant_id','approved_amount']);
            $prev_app_status = ContentLogger::where('application_id', $id)->where('status','approved')->count();
            if($prev_app_status < 1) {
                $total = DB::table('consumer_application')->select(DB::raw('count(*) as app_count'), DB::raw('SUM(approved_amount) as total_approved_amount'))->where('merchant_id', $consumerApplication->merchant_id)->whereIn('state', ['approved', 'disbursement checklist done','ready for disbursement','disbursed','nach registered','closed'])->first();
                $total_remaining_amount = $consumerApplication->merchant->max_approval_value - $total->total_approved_amount;
                if ($consumerApplication->merchant->status == 'active' && $consumerApplication->merchant->pre_status == 1 && ($consumerApplication->approved_amount > $total_remaining_amount || $total->total_approved_amount > $consumerApplication->merchant->max_approval_value || $total->app_count >= $consumerApplication->merchant->max_no_cases)) {
                    (new \App\Slack(new Request(['title' => 'Approval has been stopped', 'fields' => ['Message' => "Approval has been stopped because the approval limit is reached and " . $consumerApplication->merchant->merchant_name . " status is 'Active for Login'"], 'group' => 'Bd_sales_mgrs'])))->send();
                    return response(['main' => ['merchant_status' => false], 'data' => '<p style="word-break: break-word;">Total value of approved cases or total no. of approved cases is higher than the mentioned limit. Please increase the limit and then try to change the Status</p>'], 200);
                }
            }
        }

        if ($status == 'closed') {
            $due_amount = (new AccountingController())->getApplicationDueAmount($id);
            $isDue = $due_amount['total_due'] > 0 ? false : true;
            $r_data = ['overdue' => $isDue];
            $table = '<div class="col-md-12">';
            foreach ($due_amount as $_amt_key => $amt) {
                $table .= '<div class="col-md-12"><span>' . ucwords(str_replace('_', ' ', $_amt_key)) . '</span> <span style="float: right;font-family: sans-serif;">₹' . $amt . '</span></div><hr/>';
            }
            $table .= '<div class="btn-primary btn"><a href="/admin/payment/start_v1/' . $id . '" style="text-decoration: none;color: white;">Payment Entry</a></div></div>';
            return response(!$request->ajax() ? $r_data : ['main' => $r_data, 'data' => $table], 200);
        }

        // blocker to move the case to DCD if Aadhaar card is missing
        if ($status == 'disbursement checklist done' && empty($application->aadhaar_card)) {
            return response(['main' => ['aadhaar_missing' => false]], 200);
        }

        // blocker to move the case to DCD on Loan Agreement non signing for KM Global lender
        if ($status == 'disbursement checklist done' && $application->lender_id == 2 && $application->purpose == _env('SOLAR_CATEGORY_ID')) {
            $apiController = new ApiController();
            $isHypothecationActive = $apiController->canHypothecated($application->id);
            $requiredDoc = DB::select("select consumer_application_id, file_type from consumer_application_files where file_type in ('proforma', 'tfr', 'TFR', 'hypothecation_agreement') and consumer_application_id = ". $application->id ." and deleted_at is null");

            if ($isHypothecationActive) {
                $loanHypothecationModel = LoanHypothecationModel::where('application_id', $application->id)->whereNull('deleted_at')->orderBy('created_at', 'desc')->first(['id', 'applicant_signing', 'co_applicant_signing']);
                foreach ($requiredDoc as $doc) {
                    if ($doc->file_type == 'tfr') {
                        $hasTfr = true;
                    }
                    if ($doc->file_type == 'proforma') {
                        $hasSolarQuotation = true;
                    }
                    if ($doc->file_type == 'hypothecation_agreement') {
                        $hasHypothecationAgreement = true;
                    }
                }
                if (isset($loanHypothecationModel->id) && !isset($hasHypothecationAgreement)) {
                    if ($loanHypothecationModel->applicant_signing == 0) {
                        return response(['main' => ['loan_agreement_signing' => false]], 200);
                    }
                    if (!empty($application->co_applicant_name) && $loanHypothecationModel->co_applicant_signing == 0) {
                        return response(['main' => ['loan_agreement_signing' => false]], 200);
                    }
                }
                if (!isset($loanHypothecationModel->id) && !isset($hasHypothecationAgreement)) {
                    return response(['main' => ['loan_agreement_signing' => false]], 200);
                }

                if (!(new PostApprovalController())->checkTFRCondition($application->id)) {
                    $hasTfr = true; // Checking TFR only for ongrid-residential & housing society cases
                }
                if (!isset($hasSolarQuotation) || !isset($hasTfr) && ($application->application_element->type_of_customer_sub_category != 'Aatta Chakki')) {
                    return response(['main' => ['quotation_tfr' => false]], 200);
                }
            }
            // Check PF entry exists in case of collected by CF
            if ((isset($application->proFormaInvoice->processing_fee_by_merchant) && $application->proFormaInvoice->processing_fee_by_merchant != 1) ||
             (!isset($application->proFormaInvoice->processing_fee_by_merchant) && $application->merchant->is_collected != 1 )) {
                $paymentTransaction = $application->payment_transaction->where('payment_for', 'processing_fee')->where('deleted_at', null);
                if (empty($paymentTransaction)) {
                    return response(['main' => ['processing_fee' => false]], 200);
                } else {
                    $totalPaid = $paymentTransaction->sum('amount');
                    if ($totalPaid < $application->emi->processing_fee) {
                        return response(['main' => ['processing_fee' => false]], 200);
                    }
                }
            }
        }

        $response = [];
        $creditReport = null;
        $foir = 0;

        $documentLists = isset($data['getOtherRequiredDocument']) && isset($data['getOtherRequiredDocument']['sorted']) ? $data['getOtherRequiredDocument']['sorted'] : $this->getOtherRequiredDocument($application);

        if ($documentLists) {
            $checks = array_merge($checks, array_values($documentLists));
        }

        // Mandatory details check (field values, not documents)
        if ($application->application_element && $application->application_element->mandatory_details_list) {
            $fieldToColumnMap = [
                // application_form
                'applicant_name'              => ['column' => 'name',                           'table' => 'application'],
                'pan_number'                  => ['column' => 'pan_card',                       'table' => 'application'],
                'installation_address'        => ['column' => 'installation_address_line_1',    'table' => 'element'],
                'permanent_address'           => ['column' => 'permanent_address_line_1',       'table' => 'application'],
                'current_address'             => ['column' => 'current_address_line_1',         'table' => 'application'],
                'installation_address_status' => ['column' => 'installation_address_status',    'table' => 'element'],
                'current_address_status'      => ['column' => 'current_address_status',         'table' => 'application'],
                'permanent_address_status'    => ['column' => 'permanent_address_status',       'table' => 'application'],
                // employment_details
                'profession_type'             => ['column' => 'employee_status',                'table' => 'application'],
                'company_name'                => ['column' => 'company_name',                   'table' => 'application'],
                'income'                      => ['column' => 'monthly_income',                 'table' => 'application'],
                // solar_system_details
                'sub_category_of_solar'       => ['column' => 'type_of_customer',  'table' => 'element'],
                'power_type'                  => ['column' => 'solar_power_type',               'table' => 'element'],
                'inverter'                    => ['column' => 'inverter',                       'table' => 'element'],
                'panel_name'                  => ['column' => 'panel',                          'table' => 'element'],
                'gross_project_amount'        => ['column' => 'inverter_gross_project_amount',  'table' => 'element'],
                'e_bill_amount'               => ['column' => 'inverter_monthly_power_bill',    'table' => 'element'],
                'service_provider'            => ['column' => 'discom_service_provider',        'table' => 'element'],
                'kw'                          => ['column' => 'inverter_KW_installation',       'table' => 'element'],
                'subsidy_amount'              => ['column' => 'inverter_subsidy_amount',        'table' => 'element'],
                // lender_requirement
                'father_name'                 => ['column' => 'father_name',                    'table' => 'element'],
                'mother_name'                 => ['column' => 'mother_name',                    'table' => 'element'],
                'religion'                    => ['column' => 'applicant_religion',             'table' => 'element'],
                'employment_address'          => ['column' => 'work_address_line_1',            'table' => 'application'],
                'aadhar_number'               => ['column' => 'aadhaar_card',                   'table' => 'application'],
            ];

            $mandatoryFields = array_map('trim', explode(',', $application->application_element->mandatory_details_list));

            $detailFieldKeys = [];

            foreach ($mandatoryFields as $field) {
                if (!isset($fieldToColumnMap[$field])) {
                    continue;
                }

                $map   = $fieldToColumnMap[$field];
                $value = $map['table'] === 'application'
                            ? $application->{$map['column']}
                            : $application->application_element->{$map['column']};

                $response[$field] = !empty($value);
                $detailFieldKeys[] = $field;

                // Prevent switch default from overwriting this with a file check
                $checks = array_diff($checks, [$field]);
            }

            // Tag which response keys are detail fields (not documents)
            // so the frontend can show an edit-form link instead of a document upload box
            if (!empty($detailFieldKeys)) {
                $response['_detail_fields'] = $detailFieldKeys;
            }
        }

        foreach ($application->creditReport as $item) {
            if ($item->applicant_type == 1) {
                $creditReport = 1;
            }
        }
        foreach ($application->foir as $item) {
            if ($item->applicant_type == 1) {
                $foir = 1;
            }
        }

        $applicationFiles = [];
        $applicationFilesPath = [];
        foreach ($application->documents as $_document) {
            $applicationFiles[] = $_document->file_type;
            $applicationFilesPath[] = $_document->file_path;
        }
        $isFldgCheck = true;
        $isFldgCheckL = false;

        foreach ($checks as $check) {

            switch ($check) {
                case 'equifax_report':
                    $response[$check] = !in_array($check, $applicationFiles) ? false : true;
                    if (!$response[$check]) {
                        $response[$check] = is_null($creditReport) ? false : true;
                    }
                    break;
                case 'agreement':
                    $agreement_check = in_array('agreement', $applicationFiles);
                    $loan_agreement_esign_check = in_array('loan_agreement_esign', $applicationFiles);
                    $hypothecation_check = in_array('hypothecation_agreement', $applicationFiles);
                    $response[$check] = $agreement_check || $loan_agreement_esign_check || $hypothecation_check;
                    break;
                case 'is_ready_for_disbursement':
                    $response[$check] = $application->merchant && $application->merchant->status == 'active' && $application->merchant->pre_status == 0;
                    break;
                case 'product_name':
                    if(!$application->application_element->is_bnpl){
                        $response[$check] = $application->application_element && $application->application_element->product_name;
                    }
                    break;
                // SSE Merchant Reference Check Condition
                case 'reference_name_1':
                    if($application->approved_amount > 60000 && !$application->application_element->reference_name_1){
                        $response[$check] = $application->application_element && $application->application_element->reference_name_1;
                    }
                    break;
                case 'risk_category':
                    $response[$check] = isset($application->application_element->verify_risk_category, $application->application_element->risk_category);
                    break;
                case 'consent_check':
                    if($application->lender_id == 2){
                    $response[$check] = in_array('consent_logs', $applicationFiles);}
                    else{
                        $response[$check] = true;
                    }
                    break;
                case 'co_applicant_consent_check':
                    if(isset($application->co_applicant_name) && $application->lender_id == 2){
                        $response[$check] = in_array('co_app_consent_logs', $applicationFiles);}
                        else{
                            $response[$check] = true;
                        }
                    break;
                case 'aadhaar_masking':
                    $response[$check] = $this->strposa(['aadhar_card_masked','masked_doc'], $applicationFiles, $applicationFilesPath);
                    break;
                case 'emi_days_exceed':
                    if(!$application->application_element->is_bnpl){
                        $response[$check] = false;
                        if($application->emi){
                            if(Carbon::parse($application->emi->emi_date)->timestamp < Carbon::now()->addDays(45)->timestamp){
                                $response[$check] = true;
                            }
                        }
                    }
                    break;
                case 'legal_charges_pending':
                    if(!$application->application_element->is_bnpl){
                        $legal_charges_initial_date = "2025-01-13"; // Default date value set according to the stamp duty release
                        $approvedLog = StatusLogs::where('application_id', $application->id)->where('status', 'approved')->orderBy('created_at', 'asc')->first(['created_at']);
                        $legalChargesReleaseDate = Carbon::parse($legal_charges_initial_date);

                        if ($approvedLog) {
                            $approvedDate = Carbon::parse($approvedLog->created_at);
                            if ($legalChargesReleaseDate->gt($approvedDate)) {
                                // stamp duty release date is after the approved date
                                $response[$check] = true;
                                break;
                            }
                        }
                        $response[$check] = false;

                        $merchant_processing_collected = isset($application->proFormaInvoice) && $application->proFormaInvoice->processing_fee_by_merchant == 1 ? $application->proFormaInvoice->processing_fee_by_merchant : (isset($application->merchant->is_collected) && $application->merchant->is_collected == 1 ? $application->merchant->is_collected : 0);
                        if($merchant_processing_collected){
                            $response[$check] = true;
                        }else if($application->emi && $application->emi->legal_charges > 0){
                            foreach($application->payment_transaction as $transaction) {
                                if (is_null($transaction->is_deleted_at) && is_null($transaction->deleted_by) && $transaction->payment_for == 'legal_charges') {
                                    $response[$check] = true;
                                }
                            }
                        }else{
                            $response[$check] = true;
                        }
                    }
                    break;
                case 'lat_long':
                    if($application->application_element->type_of_customer == $this->solar_category['atta_chakki']){
                        $userGeolocation = UserGeolocation::where('_id', $application->id)->where('applicant_type', 1)->where('id_type', 'application_id')->where('service', 'cpv')->whereNull('deleted_at')->first(['latitude','longitude']);
                        if(isset($userGeolocation->latitude) && isset($userGeolocation->longitude)){
                            $response[$check] = true;
                        }else{
                            $response[$check] = false;
                        }
                    }
                    break;
                case 'first_emi_date_validation':
                    $response[$check] = false;
                    if($application->emi && $application->lender_id == 2){
                        if(Carbon::parse($application->emi->emi_date)->timestamp > Carbon::now()->addDays(20)->timestamp){
                            $response[$check] = true;
                        }
                    }else if($application->lender_id != 2){
                        $response[$check] = true;
                    }
                    break;
                case 'bank_validation':
                    $response[$check] = true;
                    $bankDisbursal = Bank::where('application_id', $id)->first(['account_number','ifsc_code','name as account_holder','karza_response']);
                    if(isset($bankDisbursal->karza_response) && $bankDisbursal->karza_response) {
                        $bank_validation = json_decode($bankDisbursal->karza_response);
                        if ((isset($bank_validation->result) && $bank_validation->result && (isset($bank_validation->result->bankTxnStatus) && $bank_validation->result->bankTxnStatus == false) || (isset($bank_validation->result->bankResponse) && ($bank_validation->result->bankResponse != 'Transaction Successful' && $bank_validation->result->bankResponse != 'SUCCESSFUL TRANSACTION'))) || !isset($bank_validation->result->bankResponse)) {
                            $response[$check] = false;
                        }
                    }else{
                        $response[$check] = false;
                    }
                    if (!$response[$check]) {
                        foreach ($applicationFiles as $file) {
                            if (stripos($file, 'bank_statement') !== false) {
                                $response[$check] = true;
                                break;
                            }
                        }
                    }
                    break;
                case 'trade_advance':
                    $response[$check] = false;

                    if($application->merchant->is_trade_advance == 1) {
                        if (!$response[$check]) {
                            if (!is_bool($this->getMultiStageDisbursementStatus($application))) {
                                $response[$check] = false;
                            } else {
                                if (!$response[$check]) {
                                    $disbursement_data = $this->getDisbursementSummary($request, $application);
                                    if ($disbursement_data['net_disbursement']) {
                                        if ((new TradeAdvanceDisbursement())->getBalanceAmount($application->merchant_id, $disbursement_data['net_disbursement']) > 0) {
                                            $response[$check] = true;
                                        }
                                    }
                                }

                                if (!$response[$check]) {
                                    $merchant = Merchant::where('id', $application->merchant_id)->first(['trade_advance_amount', 'id', 'is_trade_advance']);
                                    if ($merchant->is_trade_advance == 0) {
                                        $response[$check] = true;
                                    }
                                }
                            }
                        }
                    }else{
                        $response[$check] = true;
                    }

                    break;
                case 'bank_details':
                    //$bank_details = Bank::where('application_id', $id)->first(['id']);
                    $response[$check] = isset($application->bank_details);
                    break;
                case 'solar_addr_missing':
                    $categoryName = env('APP_CONNECTION') ? 24 : 6;
                    if ($categoryName == $application->purpose){
                        $installationData = ConsumerApplicationElement::where('application_id', $id)->first(['installation_address_line_1', 'installation_address_state', 'installation_address_city', 'installation_address_pincode']);
                        if (!empty($installationData->installation_address_city) || !empty($installationData->installation_address_line_1) || !empty($installationData->installation_address_state) || !empty($installationData->installation_address_pincode)) {
                            $response[$check] = true;
                        } else {
                            $response[$check] = false;
                        }
                    }
                    break;
                case 'current_address_proof':
                    if(($application->permanent_address_line_1 == $application->current_address_line_1) && ($application->permanent_address_state == $application->current_address_state) && ($application->permanent_address_city == $application->current_address_city) && ($application->permanent_address_pincode == $application->current_address_pincode) && ($application->permanent_address_landmark == $application->current_address_landmark) && ($application->permanent_address_status == $application->current_address_status)){
                        $response[$check] = true;
                    }else {
                        // 2. Define the list of acceptable documents for Address Proof
                        $acceptableDocs = [
                            'current_address_proof',
                            'votar_id_front', 'Votar Id Front',
                            'aadhar_card', 'Aadhar Card',
                            'aadhar_card_back', 'Aadhar Card Back',
                            'electricity_bill', 'Electricity Bill',
                            'rent_agreement', 'Rent Agreement',
                            'bank_statement', 'Bank Statement',
                            'passport_front', 'Passport Front',
                            'gas_bill', 'Gas Bill'
                        ];

                        // 3. Check if any of these documents exist in the uploaded files array
                        // array_intersect returns the common values between the two arrays
                        $uploadedAddressProof = array_intersect($acceptableDocs, $applicationFiles);
                        $response[$check] = !empty($uploadedAddressProof) ? true : false;
                    }
                    break;
                case 'pan_card':
                case 'aadhar_card':
                case 'utilitybillvalidation':
                case 'bank_statement':
                case '3_month_bank_statement':
                case '6_month_bank_statement':
                case 'sanction_letter':
                case 'pro_forma_invoice':
                case 'proforma':
                case 'gas_bill':
                case 'electricity_bill':
                case 'sale_deed':
                case 'rent_agreement':
                case 'self_attested':
                case 'cpv':
                case 'panvalidation':
                case 'is_consent':
                case 'solar_installation_proof':
                case 'aadhar_card_masked':
                case 'aadhar_card_back_masked':
                case 'pan_card_masked':
                case 'emi_date':
                case 'reference_1':
                case 'customer_photo':
                case 'aadhar_pancard_masked_osv':
                case 'virtual_acount':
                case 'liabilty_hold':
                    $response[$check] = !in_array($check, $applicationFiles) ? false : true;
                    if(!$response[$check]){
                        if(isset($application->merchant_id) && (new BNPL())->is($application->merchant_id)){
                            $response[$check] = true;
                        }
                    }
                    if (!$response[$check] && $check == 'agreement') {
                        $response[$check] = !in_array('loan_agreement_esign', $applicationFiles) ? false : true;
                    }
                    if ($application->loan_amount < 75000 && in_array($check, ['bank_statement', '3_month_bank_statement', '6_month_bank_statement'])) {
                        $response[$check] = true;
                    }

                    if (!$response[$check] && in_array($check, ['bank_statement', '3_month_bank_statement', '6_month_bank_statement'])) {
                        foreach ($applicationFiles as $file) {
                            if (stripos($file, 'bank_statement') !== false) {
                                $response[$check] = true;
                                break;
                            }
                        }
                    }

                    if ($check == 'panvalidation') {
                        $isOnValidation = (isset($application->creditReport[0]) && isset($application->creditReport[0]->panValidation)) ? true : false;
                        if ($isOnValidation == false) {
                            $isOnValidation = !in_array('panvalidation', $applicationFiles) ? false : true;
                        }
                        $isOnValidation = (bool)_env('SKIP_PAN_VALIDATION') ? true : $isOnValidation;
                        $response[$check] = $isOnValidation;
                    }

                    if(!$request->has('bot') && $status == 'waiting for decision' && $check == 'pan_card' && !$response[$check]){
                        if(!empty($application->pan_card)){
                            $response[$check] = true;
                        }
                    }
                    if($check == 'solar_installation_proof'){
                        if($this->isDisbPostInstallationCase($application->id)){
                            if(in_array($check, $applicationFiles)){
                                $response[$check] = true;
                            }else{
                                $response[$check] = false;
                            }
                        }else{
                            $response[$check] = true;
                        }

                    }
                    if($check == 'proforma' || $check == 'pro_forma_invoice'){
                        if($application->merchant){
                            $response[$check] = true;
                        }
                    }

                    if($check == 'is_consent' && $application->lender->id != 4){
                        $response[$check] = true;
                    }elseif($check == 'is_consent' && $application->lender->id == 4 && $application->application_element->is_consent == 1){
                            $response[$check] = true;
                    }

                    $aadhar_card_masked = 0;
                    $aadhar_card_back_masked = 0;
                    $pan_card_masked = 0;
                    foreach($application->documents as $key => $document){
                        $array_value = [$document->file_type];

                        if($check == 'aadhar_card_masked'){
                            if($document->file_type && $document->is_masked == 1){
                                $response[$check] = true;
                                $aadhar_card_masked = 1;
                            }
                        }
                        if($check == 'aadhar_card_back_masked'){
                            if($document->file_type && $document->is_masked == 1){
                                $response[$check] = true;
                                $aadhar_card_back_masked =1;
                            }
                        }
                        if($check == 'pan_card_masked'){
                            if($document->file_type && $document->is_masked == 1){
                                $response[$check] = true;
                                $pan_card_masked = 1;
                            }
                        }
                        if($check == 'customer_photo'){
                            if($document->file_type && $document->file_type == 'customer_photo'){
                                $response[$check] = true;
                            }
                        }
                        // For SSE Merchant -  Reference  Document check Condition
                        if($check == 'reference_1'){
                            if($application->merchant_id == _env('SSE_MERCHANT_ID') && ($application->updated_by == 'MERCHANT API')){
                                $response[$check] = true;
                            }elseif($document->file_type && $document->file_type == 'reference_1' || $application->approved_amount < 60000){
                                $response[$check] = true;
                            }
                        }
                        if($check == 'virtual_acount' && $application->merchant_id != 6474){
                                $response[$check] = true;
                        }

                        if($check == 'aadhar_pancard_masked_osv' && $application->lender->id != 4){
                            $response[$check] = true;
                        }elseif($check == 'aadhar_pancard_masked_osv' && $application->lender->id == 4){
                            if($aadhar_card_masked == 1 && $aadhar_card_back_masked == 1 && $pan_card_masked == 1){
                                $response[$check] = true;
                            }
                        }
                    }
                    break;
                case 'personal_discussion':
                    $matches = array_filter($applicationFilesPath, function($value) {
                        return str_contains($value, 'personal_discussion');
                    });
                    if (count($matches) > 0) {
                        $response[$check] = true;
                    }
                    break;
                case 'credit_approval_limit':
                    if($application->approved_amount){
                        $userApprovalLimit = User::where('id',Auth::user()->id)->whereNull('deleted_at')->first(['credit_approval_limit']);
                        if($userApprovalLimit){
                            if($userApprovalLimit->credit_approval_limit){
                                // when approval limit is greater than zero
                                $offer_details = MerchantOffers::where('id', $application->offer_id)->first();
                                $net_loan_amount = (new FrontController())->checkNetLoanAmount($offer_details, $application->approved_amount);
                                $response[$check] = $net_loan_amount <= $userApprovalLimit->credit_approval_limit ? true : false;

                                //$response[$check] = ($application->approved_amount <= $userApprovalLimit->credit_approval_limit) ? true : false;
                            }else{
                                // when approval limit is 'null' or equal to zero
                                $response[$check] = true;
                            }
                        }
                        if(!$response[$check]){
                            $stopFldgDisplay = true;
                        }
                    }
                    break;
                case 'approved_amount':
                    // if(isset($stopFldgDisplay) && $stopFldgDisplay){
                    //     $response[$check] = true;
                    // }else{
                    //     $response[$check] = false;
                    // }
                    if (!isset($application->approved_amount)) {
                        $response[$check] = false;
                    }
                    break;
                case 'disbursement_checker_limit':
                    if($application->approved_amount){
                        $userDisbursementLimit = User::where('id',Auth::user()->id)->whereNull('deleted_at')->first(['disbursement_checker_limit']);
                        if($userDisbursementLimit){
                            if($userDisbursementLimit->disbursement_checker_limit){
                                // when approval limit is greater than zero
                                $offer_details = MerchantOffers::where('id', $application->offer_id)->first();
                                $net_loan_amount = (new FrontController())->checkNetLoanAmount($offer_details, $application->approved_amount);
                                $response[$check] = ($net_loan_amount <= $userDisbursementLimit->disbursement_checker_limit) ? true : false;
                            }else{
                                // when approval limit is 'null' or equal to zero
                                $response[$check] = true;
                            }
                        }else{
                            $response[$check] = true;
                        }
                    }
                    break;
                case 'monthly_income':
                    $response[$check] = !($application->monthly_income <= 0);
                    break;
                case 'employee_status':
                    $response[$check] = !empty($application->employee_status);
                    break;
                case 'experience':
                    if($application->lender_id == AvanseServices::$lender_id) {
                        $response[$check] = !(empty($application->experience) || is_null($application->experience));
                    }
                    break;
                case 'designation':
                    if($application->lender_id == AvanseServices::$lender_id) {
                        $response[$check] = !(empty($application->application_element->designation) || is_null($application->application_element->designation));
                    }
                    break;
                case 'company_name':
                    if(!$application->application_element->is_bnpl){
                        if(in_array($application->employee_status, ['UNEMPLOYED', 'PENSIONER','HOUSEWIFE'])){
                            $response[$check] = true;
                        }else {
                            $response[$check] = !empty($application->company_name);
                        }
                    }
                    break;
                case 'atta_chakki':
                    $response[$check] = !(empty($application->application_element->credit_approval_video) || is_null($application->application_element->credit_approval_video));
                    if (!$response[$check]) {
                        $response[$check] = in_array('credit_approval_video', $applicationFiles);
                    }
                    break;
                case 'applicant_details':
                    $response[$check] = !is_null($application->name);
                    if ($response[$check]) {
                        $response[$check] = !is_null($application->mobile_number);
                    }
                    if ($response[$check] && !$application->application_element->is_bnpl && $application->application_element->type_of_customer_application != 'Non-individual') {
                        $response[$check] = !is_null($application->gender);
                    }
                    if ($response[$check]) {
                        $response[$check] = !is_null($application->dob);
                    }
                    if ($response[$check]) {
                        $response[$check] = !is_null($application->monthly_income);
                    }
                    if ($response[$check]) {
                        $response[$check] = !is_null($application->loan_amount);
                    }
                    if ($response[$check]) {
                        $response[$check] = !is_null($application->merchant_id);
                    }
                    if ($response[$check]) {
                        $response[$check] = !is_null($application->purpose);
                    }
                    if ($response[$check]) {
                        $response[$check] = !is_null($application->offer_id);
                    }
                    break;
                case 'generate_emi':
                    $response[$check] = !is_null($application->emi);
                    break;
                case 'co_applicant_for_signing':
                case 'co_applicant_for_income':
                    $response[$check] = !is_null($application->co_applicant_name);
                    break;
                case 'courier':
                    $courier = Couriers::where('documents', 'like', '%"document_for_id":"' . $id . '"%')->first(['id']);
                    $response[$check] = isset($courier->id);
                    break;
                case 'nach':
                    $response[$check] = in_array($check, $applicationFiles);
                    if (!$response[$check]) {
                        $mandate = Mandate::where('consumer_application_id', $id)->whereNotIn('status', ['inactive', 'active'])->first(['id']);
                        $response[$check] = !!isset($mandate->id);
                    }
                    if (!$response[$check]) {
                        $isNachRequired = (new NachService($request))->isCustomerHasPreviousActiveNach($application->applicant_id);
                        if ($isNachRequired) {
                            $response[$check] = true;
                        }
                    }

                    if(!$response[$check]){
                        $response[$check] = in_array('e mandate', $applicationFiles);
                    }

                    break;
                case 'security_cheques':
                    $response[$check] = !in_array($check, $applicationFiles) ? false : true;
                    if (!$response[$check]){
                        $response[$check] = !in_array('e mandate', $applicationFiles) ? false : true;
                        if (!$response[$check]){
                            $response[$check] = !in_array('e-mandate', $applicationFiles) ? false : true;
                        }

                        if($response[$check]){
                            $applicationEMICalculation  = ApplicationEMICalculation::where('application_id', $id)->first(['emi']);
                            if(isset($applicationEMICalculation->emi) && $applicationEMICalculation->emi) {
                                $mandateDataItem = Mandate::where('consumer_application_id', $id)->whereNotNull('umrn')->where('mandate_amount', '>', $applicationEMICalculation->emi)->where('umrn', '!=', '0')->where('mode','lotuspay_emandate')->where('status', 'active')->first(['id']);
                                if(!isset($mandateDataItem->id)){
                                    $response[$check] = false;
                                }
                            }else{
                                $response[$check] = false;
                            }
                        }
                    }
                    break;
                case 'credit_appraisal_memo':
                    $response[$check] = !in_array($check, $applicationFiles) ? false : true;
                    break;
                case 'fldg':
                    $isFldgCheckL = true;
                    $invoice = ProFormaInvoice::where('application_id', $application->id)->first(['id','fldg_applied', 'fldg_applied_category']);
                    if(isset($invoice->fldg_applied) && $invoice->fldg_applied == 1 && $invoice->fldg_applied_category > 0){
                        $FLDGCategory = FLDGCategory::where('merchant_id', $application->merchant->id)->where('id', $invoice->fldg_applied_category)->first(['id','available_exposure']);
                        if(!isset($FLDGCategory->available_exposure) || (isset($FLDGCategory->available_exposure) && ($FLDGCategory->available_exposure <= 0 || $FLDGCategory->available_exposure == null))){
                            $isFldgCheck = false;
                        }
                    }
                    break;
                case 'business_proof':
                    $response[$check] = !in_array($check, $applicationFiles) ? false : true;
                    if(!$response[$check]){
                        $response[$check] = !in_array('shop_act', $applicationFiles) ? false : true;
                    }
                    if(!$response[$check]){
                        $response[$check] = !in_array('gst_certificate', $applicationFiles) ? false : true;
                    }
                    if(!$response[$check]){
                        $response[$check] = !in_array('udyog_aadhaar_certificate', $applicationFiles) ? false : true;
                    }
                    break;
                case 'income_proof':
                    $response[$check] = !in_array($check, $applicationFiles) ? false : true;
                    if(!$response[$check]){
                        $response[$check] = !in_array('salary_slip', $applicationFiles) ? false : true;
                    }
                    if(!$response[$check]){
                        $response[$check] = !in_array('itr', $applicationFiles) ? false : true;
                    }
                    if(!$response[$check]){
                        $response[$check] = !in_array('FORM_16', $applicationFiles) ? false : true;
                    }
                    break;
                case 'terrace_rooftop_rights_ownership_proof':
                    $response[$check] = !in_array($check, $applicationFiles) ? false : true;
                    if(!$response[$check]){
                        $response[$check] = (!in_array('sale_deed', $applicationFiles) && !in_array('SALE_DEED', $applicationFiles)) ? false : true;
                    }
                    if(!$response[$check]){
                        $response[$check] = (!in_array('PROPERTY_TAX_INVOICE', $applicationFiles) && !in_array('property_tax_invoice', $applicationFiles)) ? false : true;
                    }
                    break;
                case 'additional_terrace_rooftop_rights_ownership_proof':
                    $response[$check] = !in_array($check, $applicationFiles) ? false : true;
                    if(!$response[$check]){
                        $response[$check] = (!in_array('Property_ownership_proof', $applicationFiles) && !in_array('property_ownership_proof', $applicationFiles)) ? false : true;
                    }
                    break;
                case 'quotation':
                    $response[$check] = !in_array('solar_quotation', $applicationFiles) ? false : true;
                    if (!$response[$check]) {
                        $response[$check] = !in_array('proforma', $applicationFiles) ? false : true;
                    }
                    break;
                case 'co_applicant_bureau_repayment_proof':
                    $response[$check] = !in_array('STATEMENT_OF_ACCOUNT', $applicationFiles) ? false : true;
                    if (!$response[$check]) {
                        $response[$check] = !in_array('EMI_DEDUCTION_BANK_STATEMENT', $applicationFiles) ? false : true;
                    }
                    break;
                case 'details_pending_as_per_lender_requirement':
                    if ($application->application_element->father_name && $application->application_element->mother_name &&
                        $application->application_element->applicant_religion && $application->aadhaar_card && $application->employee_status) {
                        $response[$check] = true;
                    }
                    $response[$check] = false;
                    break;
                case 'owner_details_to_be_included_as_co_applicant':
                    $response[$check] = in_array('co_applicant_pan_card', $applicationFiles)
                                     && in_array('co_applicant_aadhar_card', $applicationFiles)
                                     && in_array('co_applicant_aadhar_card_back', $applicationFiles);
                    break;
                case 'corrected_solar_system_details':
                    if ($application->application_element->type_of_customer && $application->application_element->type_of_customer_sub_category &&
                        $application->application_element->solar_power_type && $application->application_element->panel && $application->application_element->inverter_monthly_power_bill &&
                        $application->application_element->inverter_KW_installation && $application->application_element->inverter_gross_project_amount && 
                        $application->application_element->inverter_subsidy_amount) {
                            $response[$check] = true;
                        }
                        $response[$check] = false;
                        break;
                case 'corrected_employment_details':
                    if ($application->application_element->profession_type && $application->company_name) {
                        $response[$check] = true;
                    }
                    $response[$check] = false;
                    break;
                case 'completed_application_form_current_form_incomplete':
                    if ($application->current_address_pincode && $application->current_address_line_1 && $application->current_address_state && $application->current_address_city &&
                        $application->permanent_address_pincode && $application->permanent_address_line_1 && $application->permanent_address_state && $application->permanent_address_city &&
                        $application->application_element->installation_address_pincode && $application->application_element->installation_address_line_1 && $application->application_element->installation_address_state && $application->application_element->installation_address_city) {
                        $response[$check] = true;
                    }
                    $response[$check] = false;
                    break;
                case 'emandate':
                    $isNachRequired = (new NachService($request))->isCustomerHasPreviousActiveNach($application->applicant_id);
                    if (!$isNachRequired) {
                        $response[$check] = !isset($application->checkmandate) || !$application->checkmandate ? false : true;
                    } else {
                        $response[$check] = true;
                    }
                    break;
                case 'address':
                    $response[$check] = is_null($application->permanent_address_line_1) ? false : true;
                    if ($response[$check]) {
                        $response[$check] = is_null($application->permanent_address_state) ? false : true;
                    }
                    if ($response[$check]) {
                        $response[$check] = is_null($application->permanent_address_city) ? false : true;
                    }
                    if ($response[$check]) {
                        $response[$check] = is_null($application->permanent_address_pincode) ? false : true;
                    }
                    break;
                case 'foir':
                    $response[$check] = !in_array('equifax_report', $applicationFiles) ? false : true;
                    if (!$response[$check]) {
                        $response[$check] = $foir == 0 ? false : true;
                    }
                    break;
                case 'nominee_details':

                    if($application->purpose == 4){
                        $response[$check] = true;
                    }else if(in_array($application->purpose, [7, 24])) { //Nominee details should show only for EV and Solor Cases
                        $invoice = ProFormaInvoice::where('application_id', $application->id)->first(['id', 'insurance_premium_by_merchant', 'insurance_premium_applicable']);
                        $response[$check] = false;
                        if (isset($invoice->id) && $invoice->insurance_premium_applicable == 1) {
                            $isNominee = ConsumerApplicationElement::where('application_id', $application->id)->first(['nominee_salutation', 'nominee_full_name', 'nominee_dob', 'nominee_gender', 'nominee_relationship', 'nominee_mobile_number']);
                            $isFalse = true;
                            if ($isNominee && (isset($isNominee->nominee_salutation) && !empty($isNominee->nominee_salutation))) {
                                $response[$check] = true;
                            } else {
                                $response[$check] = false;
                                $isFalse = false;
                            }
                            if ($isFalse && $isNominee && (isset($isNominee->nominee_full_name) && !empty($isNominee->nominee_full_name))) {
                                $response[$check] = true;
                            } else {
                                $response[$check] = false;
                            }
                            if ($isFalse && $isNominee && (isset($isNominee->nominee_dob) && !empty($isNominee->nominee_dob))) {
                                $response[$check] = true;
                            } else {
                                $response[$check] = false;
                            }
                            if ($isFalse && $isNominee && (isset($isNominee->nominee_gender) && !empty($isNominee->nominee_gender))) {
                                $response[$check] = true;
                            } else {
                                $response[$check] = false;
                            }
                            if ($isFalse && $isNominee && (isset($isNominee->nominee_relationship) && !empty($isNominee->nominee_relationship))) {
                                $response[$check] = true;
                            } else {
                                $response[$check] = false;
                            }
                            if ($isFalse && $isNominee && (isset($isNominee->nominee_mobile_number) && !empty($isNominee->nominee_mobile_number))) {
                                $response[$check] = true;
                            } else {
                                $response[$check] = false;
                            }
                        } else {
                            $response[$check] = true;
                        }
                    }
                    break;
                case 'insurance_payment_receipt':
                    $invoice = ProFormaInvoice::where('application_id', $application->id)->first(['id','insurance_premium_by_merchant','insurance_premium_applicable']);

                    if(isset($invoice->id) && $invoice->insurance_premium_applicable == 1) {
                        $response[$check] = !in_array('insurance_payment_receipt', $applicationFiles) ? false : true;
                        if (!$response[$check]) {
                            $response[$check] = (!isset($invoice->id) || (isset($invoice->id) && $invoice->insurance_premium_by_merchant == 0)) ? false : true;
                        }
                        if (!$response[$check]) {
                            $insurance_fee = PaymentTransaction::where('application_id', $application->id)->where('payment_for', 'insurance_fee')->first(['id']);
                            $response[$check] = (!isset($insurance_fee->id)) ? false : true;
                        }
                    }else{
                        $response[$check] = true;
                    }
                    break;
                case 'advance_amount_receipt':
                    $invoice = ProFormaInvoice::where('application_id', $application->id)->first(['id','merchant_collected_advance_amount']);

                    if(isset($invoice->id) && $invoice->merchant_collected_advance_amount == 1 && $application->emi && $application->emi->upfront_from_customer) {
                        $response[$check] = !in_array('advance_amount_receipt', $applicationFiles) ? false : true;
                        if (!$response[$check]) {
                            $advance_amount_due = PaymentTransaction::where('application_id', $application->id)->where('payment_for', 'advance_amount')->first(['id']);
                            $response[$check] = (!isset($advance_amount_due->id)) ? false : true;
                        }
                    }else{
                        $response[$check] = true;
                    }
                    break;
                case 'kyc':
                    if(!$application->application_element->is_bnpl) {
                        $digio = KYCDetails::where('application_id', $application->id)->whereNotNull('response')->whereNull('deleted_at')->orderBy('id', 'desc')->first();
                        $onfido = OnfidoIntegration::where('application_id', $application->id)->whereNull('deleted_at')->first();
//                    $cam = ConsumerApplicationFiles::where('consumer_application_id', $application->id)->where('file_type', 'customer_cam_image')->whereNull('deleted_at')->get();
//                    $osv = ConsumerApplicationFiles::where('consumer_application_id', $application->id)->where('file_type', 'original_seen_verified')->whereNull('deleted_at')->get();
                        $video = ConsumerApplicationElement::where('application_id', $application->id)->whereNotNull('video_kyc')->first();
                        $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();

                        if(self::VKYC_VENDOR == "karza") {
                            $karza_id = KarzaVideoAttribute::where('application_id', $application->id)->whereNull('deleted_at')->orderBy('created_at', 'desc')->first(['id']);
                            if (!empty($karza_id)) {
                                $karzaDetails = KarzaVideoWebhook::where('karza_id', $karza_id->id)
                                    ->orderBy('created_at', 'desc')
                                    ->first(['data']);
                                if (isset($karzaDetails->data)) {
                                    $hyperV = json_decode($karzaDetails->data, 1);
                                    $hyperV['status'] = $hyperV['approvedByAgent'] ?? ($hyperV['approvedByAuditor'] ?? '');
                                }
                            }
                        }else {
                            $hyper_id = HypervergeVideoAttribute::where('application_id', $application->id)->orderBy('created_at', 'desc')->first(['id']);
                            if (!empty($hyper_id)) {
                                $gethyperVdetails = HypervergeWebhook::where('hyper_id', $hyper_id->id)
                                    ->where('event_type', 'vcip_kyc_status')
                                    ->orderBy('created_at', 'desc')
                                    ->first(['data']);
                                if (isset($gethyperVdetails->data)) {
                                    $hyperV = json_decode($gethyperVdetails->data, 1);
                                }
                            }
                        }

                        $files = ConsumerApplicationFiles::where('consumer_application_id', $application->id)->whereNull('deleted_at')->get(['file_type']);
                        $customer_cam_image = false;
                        $self_attested = false;
                        $original_seen_verified = false;
                        if (!empty($files)) {
                            foreach ($files as $file) {
                                if ($file->file_type == 'customer_cam_image') {
                                    $customer_cam_image = true;
                                } else if ($file->file_type == 'self_attested') {
                                    $self_attested = true;
                                } else if ($file->file_type == 'original_seen_verified') {
                                    $original_seen_verified = true;
                                }
                            }
                        }

                        // Status APPROVED for hyperverge and ACCEPTED for karza
                        if (!empty($digio) || !empty($onfido) || !empty($video) || !empty($photo_kyc) || $customer_cam_image || ($self_attested && $original_seen_verified)
                            || (isset($hyperV) && isset($hyperV['status']) && ($hyperV['status'] == 'APPROVED' || $hyperV['status'] == 'ACCEPTED'))) {
                            $response[$check] = true;
                        } else {
                            $response[$check] = false;
                        }
                    }

                    break;
                // case 'reference':
                //     $response[$check] = $this->getRefferenceValidation($application) ? true : false;
                //     break;
                case 'emi_mandate_check':
                    $response[$check] = false;
                    $mandateData = Mandate::where('consumer_application_id', $application->id)->whereIn('status',['active', 1, 'submitted'])->where('mode','lotuspay_emandate')->get(['id','date_first_collection']);
                    $emiCalculation = ApplicationEMICalculation::where('application_id', $application->id)->first(['id', 'emi_date']);
                    foreach ($mandateData as $mandate) {
                        if(!$response[$check]) {
                            if (isset($mandate->id) && isset($emiCalculation->id) && date('Y-m-d', strtotime($mandate->date_first_collection)) <= date('Y-m-d', strtotime($emiCalculation->emi_date))) {
                                $response[$check] = true;
                            } else if (isset($mandate->id)) {
                                $jobProvider = JobProvider::where('application_id', $application->id)->where('from', 'first_installment_mandate_date_mismatch')->first(['id']);
                                if (!isset($jobProvider->id)) {
                                    $link = asset("admin/consumer-applications/edit/" . $application->id);
                                    $payload = [
                                        'payload' => json_encode(['id' => $application->id, 'name' => $application->name, 'merchant_name' => $application->merchant->merchant_name, 'link' => $link]),
                                        'from' => 'first_installment_mandate_date_mismatch',
                                        'application_id' => $application->id,
                                        'available_at' => Carbon::now()->toDateTimeString(),
                                        'created_at' => Carbon::now()->toDateTimeString()
                                    ];
                                    JobProvider::insert($payload);
                                }

                            } else {
                                $response[$check] = true;
                            }
                        }
                    }

                    if(!count($mandateData)){
                        $response[$check] = true;
                    }

                    break;
                default :
                    $originalCheck = $check;
                    $response[$originalCheck] = !in_array($originalCheck, $applicationFiles) ? false : true;
                    if (!$response[$originalCheck]) {
                        $check = str_replace('_', ' ', $check);
                        $response[$check] = !in_array($check, $applicationFiles) ? false : true;
                        
                        if (!$response[$check]) {
                            $normalizedCheck = strtolower(str_replace([' ', '-', '_'], '', $originalCheck));
                            foreach ($applicationFiles as $file) {
                                if (strtolower(str_replace([' ', '-', '_'], '', $file)) === $normalizedCheck) {
                                    $response[$check] = true;
                                    break;
                                }
                            }
                        }
                    }
                    if (!$response[$check] && $check == 'agreement') {
                        $response[$check] = !in_array('loan_agreement_esign', $applicationFiles) ? false : true;
                    }
                    if ($application->loan_amount < 75000 && in_array($check, ['bank_statement', '3_month_bank_statement', '6_month_bank_statement'])) {
                        $response[$check] = true;
                    }

                    if (!$response[$check] && in_array($check, ['bank_statement', '3_month_bank_statement', '6_month_bank_statement'])) {
                        foreach ($applicationFiles as $file) {
                            if (stripos($file, 'bank_statement') !== false) {
                                $response[$check] = true;
                                break;
                            }
                        }
                    }

                    if ($check == 'panvalidation') {
                        $isOnValidation = (isset($application->creditReport[0]) && isset($application->creditReport[0]->panValidation)) ? true : false;
                        if ($isOnValidation == false) {
                            $isOnValidation = !in_array($check, $applicationFiles) ? false : true;
                        }

                        $response[$check] = $isOnValidation;
                    }
                    if (str_replace(' ', '_', $check) != $check) {
                        $response[str_replace(' ', '_', $check)] = $response[$check];
                        unset($response[$check]);
                    }

                    if (isset($response[str_replace(' ', '_', $check)]) && !$response[str_replace(' ', '_', $check)]) {
                        if (str_replace('_', ' ', ucwords($check)) != $check) {
                            $response[str_replace(' ', '_', $check)] = !in_array(str_replace('_', ' ', ucwords($check)), $applicationFiles) ? false : true;
                        }
                    }

                    break;
            }
        }


        $responseValues = array_unique(array_values(array_diff_key($response, ['_detail_fields' => true])));

        if($isFldgCheckL){
            $response['fldg'] = $isFldgCheck;
            $responseValues = array_unique(array_values(array_diff_key($response, ['_detail_fields' => true])));
        }

        if ($application->emi && $application->activeOffer) {
            $offer_linked_pf = (new RiskController(new Request()))->getOfferLinkedPF($application);
            $total_pf = round($offer_linked_pf) + $application->emi->pf_surcharge_amount + $application->emi->pf_surcharge_gst;
            $pfSurchargePercent = $application->emi->pf_surcharge_percent;
        }

        if ($status == 'waiting for decision') {
            $autodecisionCheckresponse = (new autoBRE())->checkAutoBREStatus($id);
            $approvedAmount = isset($application) ? $application->approved_amount : null;

            $cwFactory = new CloudWatchLoggerFactory();
            $cwFactory->logger(json_encode(["application_id" => $id, "title" => "autoBRE", "response" => $autodecisionCheckresponse->getData()]));
            if($autodecisionCheckresponse->getData() && $autodecisionCheckresponse->getData()->status == 'FAIL'){
                return $autodecisionCheckresponse;
            }

            // --- Handling auto-decision ---
            if (
                !$request->has('bot') &&
                count($responseValues) == 1 &&
                isset($responseValues[0]) &&
                ($responseValues[0] || isset($response['approved_amount'])) &&
                ($autoDecisionOnWaitingForDecision = $this->autoDecisionOnWaitingForDecision($request, $status, $id, false))
            ) {
                // Handling this because we don't want to return approved_amount key if case is not ran by residual foir logic of table of offers

                $approvedAmountNew = isset($application) ? $application->fresh()->approved_amount : null;
                // Case 1: Boolean
                $approved_amount_changed = false;
                if($approvedAmount != $approvedAmountNew) {
                    $approved_amount_changed = true;
                } else {
                    $approvedAmountNew = $approvedAmount;
                }
                if (is_bool($autoDecisionOnWaitingForDecision)) {
                    return response()->json($response, 200);
                }

                // Case 2: Array
                if (is_array($autoDecisionOnWaitingForDecision)) {
                    return response()->json($autoDecisionOnWaitingForDecision, 200);
                }

                // Case 3: Illuminate\Http\Response
                if ($autoDecisionOnWaitingForDecision instanceof \Illuminate\Http\Response) {
                    $data = json_decode($autoDecisionOnWaitingForDecision->getContent(), true);
                    if (isset($approvedAmountNew) && $approved_amount_changed && isset($data['auto_approved'])) {
                        $data['approved_amount_residual'] = $approvedAmountNew;
                    }
                    $autoDecisionOnWaitingForDecision->setContent(json_encode($data));
                    return $autoDecisionOnWaitingForDecision;
                }

                // Fallback
                return $autoDecisionOnWaitingForDecision;
            }
        }

        $riskBasedCalculation = DB::selectOne("SELECT id, adjustment_type, adjustment_value_type, adjustment_value from risk_based_pricing_calculation where application_id = $id and deleted_at is null");
        if (isset($riskBasedCalculation->id)) {
            $response['adjustPF'] = true;
            $response['adjustType'] = $riskBasedCalculation->adjustment_type;
            $response['pfValueType'] = $riskBasedCalculation->adjustment_value_type;
            $response['pfValue'] = $riskBasedCalculation->adjustment_value;
        }
        $response['offer_linked_pf'] = isset($offer_linked_pf) ? round($offer_linked_pf): '';
        $response['total_pf'] = isset($total_pf) ? $total_pf : 0;
        $response['subv_type'] = $application->activeOffer->subvention_type_id ?? '';
        $response['pf_surcharge_percent'] = isset($pfSurchargePercent) ? $pfSurchargePercent : 0;
        // phase details passed for emi date logic
        $disbursement_offers_data = DisbursementOffers::where('application_id', $application->id)->where('offer_id', $application->offer_id)->whereNull('deleted_at')->orderby('phase', 'asc')->get()->keyby('phase');
        $total_phases = $disbursement_offers_data->count();
        $response['phase'] = $total_phases;
        $validationPassed = true;
        foreach ($response as $key => $value) {
            if ($value === false) {
                $validationPassed = false;
                break;
            }
        }
        if ($status == 'approved' && $validationPassed) {
            $response['show_popup'] = true;
        }
        return response()->json($response, 200);
    }

    public function autoDecisionOnWaitingForDecision(Request $request, $status, $id, $communication = true)
    {
        if ($status == 'waiting for decision' && !$request->has('bot')) {
            $testImport = new TestImport(new Request());
            $requestID = $testImport->random_strings(8);
            $request->merge(['request_ap_id' => $requestID]);
            $gradeController = new GradeController($request);

            $request->attributes->add(['communication' => $communication]);

            if ($gradeStatus = $gradeController->autoApproveInit($id)) {
                return $gradeStatus;
            } else if ($gradeController->pre_approvalCheck($gradeController, $id)) {
                $application = ConsumerApplication::where('id', $id)->first(['merchant_id']);
                $document_rule_id = $gradeController->initAutoDocumentation($gradeController, $id, false);
                if($application->merchant_id != 6543) {
                    $this->sendPreApprovalCommunication($id, $document_rule_id);
                    $this->sendAutoPreApprovalCommunication($id);

                }
                $consumer_application = ConsumerApplication::find($id);
                $consumer_application->state = "pre approved";
                $consumer_application->save();

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

                \Session::flash('success', 'Application is pre approved');
                return response(['pre_approved' => true], 200);
            } else if ($communication) {
                $gradeController->initAutoDocumentation($gradeController, $id);
                return true;
            }
        }
        return false;
    }

    public function checkRequestedURI($id)
    {
        $type = 'merchant';
        $requestURI = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';
        if (strpos($requestURI, 'lead/' . $id) !== false) {
            $type = 'lead';
        }
        if (strpos($requestURI, 'merchant_location/' . $id) !== false) {
            $type = 'merchant_location';
        }
        if ($requestURI) {
            $basePath = explode($id, $requestURI);
            $basePath = explode('/', $basePath[0]);
            if (in_array($type, $basePath)) {
                return $type;
            }
        }
        return false;
    }

    public function isDocumentExist($id, $name)
    {
        $file = ConsumerApplicationFiles::where('consumer_application_id', $id)->where('file_type', 'like', '%' . $name . '%')->first(['id']);
        return isset($file->id) ? true : false;
    }

    public function viewFile($id, $prefix, $key = null, $tsm = null, $temp = false)
    {
         try {
             $actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";

             if (strpos($actual_link, 'pwa') !== false || $tsm) {
                 $hashids = new Hashids('Creditfair by CS', 20);
                 if ($tsm) {
                     $time = $hashids->decode($tsm)[0];
                     if ($time < time()) {
                         //header($_SERVER['SERVER_PROTOCOL'] . ' 400 Bad Request');
                         //exit;
                     }
                 } else {
                     //header($_SERVER['SERVER_PROTOCOL'] . ' 400 Bad Request');
                     //exit;
                 }
             }

             if (!Auth::check()) {
                 $allowed_hosts = array('partner.creditfair.in', 'creditfair.in');
                 if (!isset($_SERVER['HTTP_HOST']) || !in_array($_SERVER['HTTP_HOST'], $allowed_hosts)) {
                     //header($_SERVER['SERVER_PROTOCOL'] . ' 400 Bad Request');
                     //exit;
                 }
             }

             if ($basePath = $this->checkRequestedURI($id)) {
                 $id = $basePath . '/' . $id;
             }

             if($temp){
                 $s3 = Storage::disk('s3_temp');
             } else{
                 $s3 = Storage::disk('s3');
             }

             $extension = 'pdf'; // default
             if (strpos($prefix, 'call_recording') !== false || strpos($prefix, 'call_recoding') !== false) {
                 $extension = 'mp3';
             }

             $path = storage_path() . '/' . time();

             if ($this->isInternal) {
                 $path = $path . '_' . $this->generateRandomString() . '.' . $extension;
             } else {
                 $path = $path . '.' . $extension;
             }

             if ($key && !$temp) {
                 $key = '/' . $key;
             }

             if(isset($prefix[0]) && $prefix[0] == 'LEGAL'){
                 $path1 = $prefix[1];
                 $view = $s3->get($path1);
             }else{
                $d = $id . '/' . $prefix . (empty($key) ? '': $key);
                 $view = $s3->get($d);
             }


             if (strpos($key, '.bin') !== false) {
                 $path = storage_path() . '/' . time() . '.' . explode('.', $prefix)[1];
             }
             $file = fopen($path, "w");
             fwrite($file, $view);
             fclose($file);
             if (strpos($key, '.bin') !== false) {
                 return response()->download($path)->deleteFileAfterSend(true);
             }
             else if(strpos($key , '.html')  !== false || strpos($prefix , '.html')  !== false || strpos($prefix , '.csv')  !== false){
                return response()->download($path, $prefix, [
                    'Content-Type' => 'application/octet-stream',
                    'Content-Disposition' => 'attachment; filename="' . $prefix . '"'
                ]);
             }
             else {
                 if ($this->isInternal) {
                     return $path;
                 } else {
                     return response()->file($path)->deleteFileAfterSend(true);
                 }
             }
         } catch (\Exception $e) {

             $cwFactory = new CloudWatchLoggerFactory();
             $data = array(
                 'application_id' => $id, 
                 'user_id' => isset(Auth::user()->id) ? Auth::user()->id : '',
                 'vendor' => 's3_view_file', // Changed from 'exotel' to reflect this specific function
                 'message' => $e->getMessage(), 
                 'line' => $e->getLine(), 
                 'trace' => $e->getTraceAsString()
             );
             $cwFactory->logger(json_encode($data));

             if ($prefix == 'merchant_disbursed.pdf' && $this->invoiceCounter) {
                 $this->invoiceCounter = false;
                 $this->invokeCommunication($id, true);
                 return $this->viewFile($id, $prefix, $key);
             } else if ($prefix == 'Processing Fee Invoice.pdf' && $this->invoiceCounter) {
                 $this->invoiceCounter = false;
                 $this->sendProcessingFeePDF($id, true);
                 return $this->viewFile($id, $prefix, $key);
             } else if (strpos($prefix, 'aadhar_card') !== false) {
                 $temp = true;
                 return $this->viewFile($id, $prefix, $key, null, $temp);
             }
             return '';
         }
    }

    public function generateRandomString($length = 10)
    {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        return $randomString;
    }

    public function createPhysicalMandate(Request $request)
    {
        $nach = new \App\Http\Controllers\NachController();
        $response = $nach->createMandate($request->get('id'), 'physical', $request->get('frequency'));
        $data = json_decode($response);
        if (isset($data->error) && isset($data->error->error)) {
            $data = $data->error->error;
            $message = (isset($data->message) ? $data->message : '');
            return json_encode(array("status" => "FAIL", "message" => $message));
        }
        return $response;
    }

    public function validateRequest($application)
    {
        $admin_edit = '/admin/consumer-applications/edit/' . $application->id . '?href=nav-personal-details-tab';
        if (empty($application->employee_status)) {
            return ['error' => 'Employee status is missing', 'url' => $admin_edit];
        }
        if (empty($application->company)) {
            return ['error' => 'Company is missing', 'url' => $admin_edit];
        }

        return false;
    }

    public function strposa($haystack, $needles=array(), $needlesSec = array()) {
        $status = false;
        foreach($haystack as $item) {
            foreach ($needles as $needle) {
                if ($item == preg_replace('/[0-9]+/', '', $needle)) {
                    $status = true;
                    break;
                }
            }

            if(!$status && $needlesSec){
                foreach ($needlesSec as $needleSec) {
                    if (strpos($needleSec,$item) !== false) {
                        $status = true;
                        break;
                    }
                }
            }
        }
        return $status;
    }

    public function getPanCardDetails(Request $request)
    {
        $document_type = $request->has('type') ? $request->get('type') : 'aadhaar_card';
        $filePath = '';
        $s3_path = '';
        $id = 0;
        if ($request->hasFile('document') || $request->has('link')) {
            if($request->hasFile('document')){
                $file = $request->file('document');
                $fileBase64 = base64_encode(file_get_contents($file));
                $id = $request->get('id');
                if ($id && !empty($request->get('type'))) {
//                    (new Slack(new Request(['title' => '#1', 'fields' => ['id' => $id,'filepath' => $request->get('type')], 'group' => Slack::$STAGE_TESTING])))->send();
                    $filePath = $this->uploadDocumentOnOCR($id, $request, $file, $request->get('type'), true);
                    if(strpos($request->get('type'),'aadhar_card') !== false){
                        $links = explode('/', $filePath);
                        $s3_path = $links[3] . '/' . $links[4] .'/'. $links[5];
                        $extension = explode('.', $links[5]);
                        $extension = $extension[count($extension) - 1];
                    }
                } else { // for new applications

                    $fileName = time() . '_' . $file->getClientOriginalName();
                    $s3_path = Storage::disk('s3')->putFileAs('temp', $file, $fileName);

                    // $filePath = time() . '_' . $file->getClientOriginalName();
                    // $s3_path = Storage::disk('www')->put($filePath, $file);
                    // $filePath = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . '/content/media/' . $s3_path;

                    // $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https" : "http";
                    // $filePath = $scheme . '://' . $_SERVER['HTTP_HOST'] . '/content/media/' . $s3_path;

                    // Expire in 5 minutes
                    $expiry = now()->addMinutes(5);

                    // Creating s3 presigned url 
                    $filePath = Storage::disk('s3')->temporaryUrl(
                        $s3_path,
                        $expiry
                    );

                    $extension = $file->getClientOriginalName();
                }
            }else{
                $id = $request->get('id');
                $link=$request->get('link');
                $links = explode('/', $link);
                if(isset($links[6])){
                    $s3_path = $links[4] . '/' . $links[5] .'/'. $links[6];
                }else{
                    $s3_path = $links[4] . '/' . $links[5];
                }
                $extension = explode('.', isset($links[6]) ? $links[6] : $links[5]);
                $extension = count($extension) > 1 ? $extension[count($extension) - 1] : '.jpeg';
                if(strpos($document_type, 'aadhar_card') !== false){
                    $s3 = Storage::disk('s3_temp');
                    $filePath = 'https://' . _env('AWS_TEMP_BUCKET') . _env('AWS_ORIGIN') . '/' . $s3_path;
                    if(!$s3->exists($s3_path)){
                        $s3 = Storage::disk('s3');
                        $filePath = 'https://'._env('AWS_BUCKET')._env('AWS_ORIGIN') . '/' .$s3_path;
                    }
                } else{
                    $s3 = Storage::disk('s3');
                    $filePath = 'https://'._env('AWS_BUCKET')._env('AWS_ORIGIN') . '/' .$s3_path;
                }
                $s3->setVisibility($s3_path, OCRRecognition::PUBLIC);
            }
        }

        if ($filePath) {
            $request = new Request(['file_type' => $filePath, 'file_base64'=>!empty($fileBase64) ? $fileBase64 : '', 'link' => true, 'type' => strpos($document_type, 'aadhar_card') !== false ? 'aadhaar_card' : $document_type, 'auto_mask' => strpos($document_type, 'aadhar_card') !== false ? true : false, 'id' => $id]);
            $data = (new OCRRecognition($request))->get();
            if ($data) {
                // Redundant masking logic removed here as it is handled within OCRRecognition::get()
                // Only keep the fallback upload logic if necessary, but strictly check for a valid document name
                if ($id && empty($request->get('type')) && isset($file) && isset($data['document']) && is_string($data['document'])) {
                    if($data['document'] == 'aadhar_card' || $data['document'] == 'Aadhaar Front Top' || $data['document'] == 'Aadhaar Front Bottom' || $data['document'] == 'Aadhaar Back') {
                        $this->uploadDocumentOnOCR($id, $request, $file, 'aadhar_card');
                    }else{
                        $this->uploadDocumentOnOCR($id, $request, $file, $data['document']);
                    }
                }

                if(isset($data['name']) && $data['name']){
                    $data = array_merge($data, (new ConsumerApplication())->getNameSplitAttribute(1, $data['name']));
                }

                return $data;
            }
        }

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

    public function getFileURL($s3, $s3_path, $filePath){
        Storage::disk('www')->put($filePath, $s3->get($s3_path));
        return $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . '/content/media/' . $filePath;
    }

    public function saveMandatoryDocument($id, Request $request)
    {
        $status = 'FAIL';
        $message = ''; 

        if ($request->has('mandatory_document_list') && $id > 0) {
            $existing_element = ConsumerApplicationElement::where('application_id', $id)->first(['mandatory_document_list', 'mandatory_details_list']);
            $advisorDetails = DB::SelectOne("select u.id, u.name, ca.name as application_name from users u inner join consumer_application ca on u.id = ca.created_by where ca.id = ?", [$id]);

            $existing_full_list = [];
            if(!empty($existing_element->mandatory_document_list)) $existing_full_list[] = $existing_element->mandatory_document_list;
            if(!empty($existing_element->mandatory_details_list)) $existing_full_list[] = $existing_element->mandatory_details_list;
            $existing_full_list_str = implode(',', $existing_full_list);

            if($existing_full_list_str != $request->get('mandatory_document_list')){

                if(!in_array($request->get('status'),['in-process','form completed','incomplete form'])){
                    $existdoclist = explode(',',$existing_full_list_str);
                    $newdoclist = explode(',',$request->get('mandatory_document_list'));
                    $difflistadd = implode(',',array_values(array_diff($newdoclist,$existdoclist)));
                    $difflistremove = implode(',',array_values(array_diff($existdoclist,$newdoclist)));
                    $existlist = implode(',',array_values(array_intersect($existdoclist,$newdoclist)));

                    ContentLogger::insert([
                        'application_id' => $id,
                        'data' => json_encode(['mandatoryDocList' => ['old'=>$existing_full_list_str,'new'=>$request->get('mandatory_document_list'),'existed'=>$existlist,'old'=>$difflistremove,'new'=>$difflistadd]]),
                        'status' => $request->get('status'),
                        'created_at' => Carbon::now()->toDateTimeString(),
                        'user_id' => Auth::user()->id
                    ]);
                }
                $docMapping = [
                    'electricity_bill'                    => ['category' => 'electricity_bill',                    'rule' => 'ALL',     'docs' => ['ELECTRICITY_BILL']],
                    'rent_agreement'                      => ['category' => 'rent_agreement',                      'rule' => 'ALL',     'docs' => ['RENT_AGREEMENT']],
                    'sale_deed'                           => ['category' => 'sale_deed',                           'rule' => 'ALL',     'docs' => ['SALE_DEED']],
                    'pan_card'                            => ['category' => 'pan_card',                            'rule' => 'ALL',     'docs' => ['PAN']],
                    'bank_statement'                      => ['category' => 'bank_statement',              'rule' => 'ALL',     'docs' => ['BANK_STATEMENT']],
                    'gas_bill'                            => ['category' => 'gas_bill',                            'rule' => 'ALL',     'docs' => ['GAS_BILL']],
                    'aadhar_card'                         => ['category' => 'aadhar_card',                         'rule' => 'ALL',     'docs' => ['APPLICANT_AADHAAR_FRONT', 'APPLICANT_AADHAAR_BACK']],
                    'current_address_proof'               => ['category' => 'current_address_proof',               'rule' => 'ANY_ONE', 'docs' => ['VOTAR_ID_FRONT','VOTAR_ID_BACK','APPLICANT_AADHAAR_FRONT', 'APPLICANT_AADHAAR_BACK', 'ELECTRICITY_BILL', 'RENT_AGREEMENT', 'BANK_STATEMENT', 'PASSPORT', 'GAS_BILL', 'UTILITY_BILL_VALIDATION']],
                    'business_proof'                      => ['category' => 'business_proof',                      'rule' => 'ANY_ONE', 'docs' => ['SHOP_ACT', 'GST_CERTIFICATE', 'UDYOG_AADHAR_CERTIFICATE']],
                    'income_proof'                        => ['category' => 'income_proof',                        'rule' => 'ANY_ONE', 'docs' => ['SALARY_SLIP', 'ITR', 'FORM_16']],
                    'co_applicant_bureau_repayment_proof' => ['category' => 'co_applicant_bureau_repayment_proof', 'rule' => 'ANY_ONE', 'docs' => ['STATEMENT_OF_ACCOUNT', 'EMI_DEDUCTION_BANK_STATEMENT']],
                    'owner_details_to_be_included_as_co_applicant' => ['category' => 'owner_details_to_be_included_as_co_applicant', 'rule' => 'ALL', 'docs' => ['CO_APPLICANT_PAN', 'CO_APPLICANT_AADHAAR_FRONT', 'CO_APPLICANT_AADHAAR_BACK']],
                    'emandate'                            => ['category' => 'e_mandate',                           'type' => 'INFO',    'message' => 'E-mandate is mandatory for this application'],
                    'cpv'                                 => ['category' => 'cpv',                                 'type' => 'INFO',    'message' => 'Field visit is mandatory for this application'],
                    'personal_discussion'                 => ['category' => 'personal_discussion',                 'type' => 'INFO',    'message' => 'Personal Discussion (PD)'],
                    'terrace_rooftop_rights_ownership_proof' => ['category' => 'terrace_rooftop_rights_ownership_proof', 'rule' => 'ANY_ONE',     'docs' => ['SALE_DEED','PROPERTY_TAX_INVOICE']],
                    'additional_terrace_rooftop_rights_ownership_proof' => ['category' => 'additional_terrace_rooftop_rights_ownership_proof', 'rule' => 'ALL',     'docs' => ['PROPERTY_OWNERSHIP_PROOF']],
                    'proforma'                            => ['category' => 'SOLAR_QUOTATION',                            'rule' => 'ALL',     'docs' => ['SOLAR_QUOTATION']],
                    'atta_chakki'                         => ['exclude' => true],
                ];

                $fieldCategories = [
                    'application_form' => [
                        'applicant_name', 'pan_number', 'installation_address', 'permanent_address',
                        'current_address', 'installation_address_status', 'current_address_status',
                        'permanent_address_status'
                    ],
                    'employment_details' => [
                        'profession_type', 'company_name', 'income'
                    ],
                    'solar_system_details' => [
                        'sub_category_of_solar', 'power_type', 'inverter', 'panel_name',
                        'gross_project_amount', 'e_bill_amount', 'service_provider', 'kw', 'subsidy_amount'
                    ],
                    'additional_requirement' => [
                        'father_name', 'mother_name', 'religion', 'employment_address', 'aadhar_number'
                    ]
                ];

                // Flatten all field names for easy lookup
                $allFields = [];
                foreach ($fieldCategories as $category => $fields) { 
                    foreach ($fields as $field) {
                        $allFields[] = $field;
                    }
                }

                $full_list = explode(',', $request->get('mandatory_document_list'));
                $mandatory_documents = [];
                $mandatory_details = [];

                foreach ($full_list as $item) {
                    $item = trim($item);
                    if (empty($item)) continue;

                    // Check if this item is a detail field
                    if (in_array($item, $allFields)) {
                        $mandatory_details[] = $item;
                    } else {
                        // It's a document
                        $mandatory_documents[] = $item;
                    }
                }

                ConsumerApplicationElement::where('application_id', $id)->update([
                    'mandatory_document_list' => implode(',', $mandatory_documents),
                    'mandatory_details_list' => implode(',', $mandatory_details)
                ]);

                \Log::info('Application ID: ' . $id . ' - Database updated with documents: ' . implode(',', $mandatory_documents));
                \Log::info('Application ID: ' . $id . ' - Database updated with details: ' . implode(',', $mandatory_details));

                // Merchant webhook trigger here
                if (($request->has('mandatory_document_list') && $request->get('mandatory_document_list') != "") || count($mandatory_documents) > 0) {
                    $document_requirements = [];
                    $update_fields_map = []; // category => [fields]

                    // Process only the documents (not detail fields)
                    foreach ($mandatory_documents as $doc) {
                        $doc = trim($doc);
                        if (empty($doc)) continue;

                        if (isset($docMapping[$doc])) {
                            if (isset($docMapping[$doc]['exclude']) && $docMapping[$doc]['exclude']) {
                                continue;
                            }
                            $document_requirements[] = $docMapping[$doc];
                        } else {
                            // Other documents or standard items not in docMapping
                            $document_requirements[] = [
                                'category' => 'other',
                                'rule' => 'ALL',
                                'docs' => [strtoupper(str_replace(' ', '_', $doc))]
                            ];
                        }
                    }

                    // Process only the detail fields
                    $excludeFromWebhook = ['religion'];
                    $fieldNameMap = [
                        'applicant_name' => 'name',
                        'pan_number' => 'panNumber',
                        'aadhar_number' => 'aadharNumber',
                        'father_name' => 'fatherName',
                        'mother_name' => 'motherName',
                        'sub_category_of_solar' => 'typeOfCustomer',
                        'power_type' => 'solarPowerType',
                        'inverter' => 'inverterToBeInstalled',
                        'panel_name' => 'panelToBeInstalled',
                        'gross_project_amount' => 'grossProjectValue',
                        'e_bill_amount' => 'monthlyPowerBill',
                        'service_provider' => 'service_provider',
                        'kw' => 'kwInstallation',
                        'subsidy_amount' => 'subsidyAmount',
                        'income' => 'monthly_income',
                    ];
                    foreach ($mandatory_details as $doc) {
                        $doc = trim($doc);
                        if (empty($doc)) continue;
                        if (in_array($doc, $excludeFromWebhook)) continue;

                        $fieldName = isset($fieldNameMap[$doc]) ? $fieldNameMap[$doc] : $doc;
                        foreach ($fieldCategories as $category => $fields) {
                            if (in_array($doc, $fields)) {
                                $update_fields_map[$category][] = $fieldName;

                                // Auto-inject related address sub-fields
                                if ($doc == 'installation_address') {
                                    $update_fields_map[$category][] = 'installation_address_city';
                                    $update_fields_map[$category][] = 'installation_address_pincode';
                                    $update_fields_map[$category][] = 'installation_address_state';
                                }
                                if ($doc == 'permanent_address') {
                                    $update_fields_map[$category][] = 'permanent_address_city';
                                    $update_fields_map[$category][] = 'permanent_address_pincode';
                                    $update_fields_map[$category][] = 'permanent_address_state';
                                }
                                if ($doc == 'current_address') {
                                    $update_fields_map[$category][] = 'current_address_city';
                                    $update_fields_map[$category][] = 'current_address_pincode';
                                    $update_fields_map[$category][] = 'current_address_state';
                                    $update_fields_map[$category][] = 'current_address_status';
                                }

                                break;
                            }
                        }
                    }

                    $update_fields = [];
                    foreach ($update_fields_map as $category => $fields) {
                        $update_fields[] = [
                            'category' => $category,
                            'fields' => array_values(array_unique($fields))
                        ];
                    }

                    if (in_array('owner_details_to_be_included_as_co_applicant', $mandatory_documents)) {
                        $update_fields[] = [
                            'category' => 'co_applicant_details',
                            'fields' => [
                                'co_applicant_name',
                                'co_applicant_mobile_number',
                                'co_applicant_email',
                                'co_applicant_gender',
                                'co_applicant_dob',
                                'co_applicant_relation',
                                'co_applicant_father_name',
                                'co_applicant_aadhar',
                                'co_applicant_pan',
                                'co_applicant_address_status',
                                'co_applicant_address',
                                'co_applicant_city',
                                'co_applicant_state',
                                'co_applicant_pincode',
                                'co_applicant_employment_status'
                            ]
                        ];
                    }

                    $webhookData = [
                        'document_requirements' => $document_requirements,
                        'update_fields' => $update_fields
                    ];

                    $this->webhook($id, ['type' => 'Mandatory-Document-Webhook', 'status' => $request->get('status'), 'data' => $webhookData]);
                    (new ApiController())->updateComments(Input::merge([
                        'application_id' => $id,
                        'id' => Auth::user()->id,
                        'advisor_id' => isset($advisorDetails) ? $advisorDetails->id : null,
                        'application_name' => isset($advisorDetails) ? $advisorDetails->application_name : null,
                        'show_merchant' => 1,
                    ]), 1);
                }
                $element = ConsumerApplicationElement::where('application_id', $id)->first(['mandatory_document_list', 'mandatory_details_list']);
                if((isset($element->mandatory_document_list) && !empty($element->mandatory_document_list)) || (isset($element->mandatory_details_list) && !empty($element->mandatory_details_list))) {

                    $new_list = $request->has('mandatory_document_list') ? implode(',', $mandatory_documents) : '';
                    if(isset($new_list) && $new_list != ''){
                        MandatoryDocumentListLogs::insert([
                            'application_id' => $id,
                            'user_id' => Auth::user()->id,
                            'mandatory_document_list' => $new_list,
                            'created_at' => Carbon::now()->toDateTimeString()
                        ]);
                    }

                }else {
                    MandatoryDocumentListLogs::insert([
                        'application_id' => $id,
                        'user_id' => Auth::user()->id,
                        'mandatory_document_list' => '',
                        'created_at' => Carbon::now()->toDateTimeString()
                    ]);
                }

                $status = 'OK';
                $message = 'Saved successfully';
            }
            else{
                $status = 'DUPLICATE';
                $message = 'This document is already saved';
            }
        }
        return \response()->json(['status' => $status, 'message' => $message]);
    }

    public function getChequeDetails(Request $request)
    {
        $filePath = '';
        $id = 0;
        if ($request->hasFile('document')) {
            $file = $request->file('document');
            $id = $request->get('id');
            $filePath = $this->uploadDocumentOnOCR($id, $request, $file, 'cheque', false);

            if ($request->get('type') == 'consumer') {
                $files = new ConsumerApplicationFiles();
                $files->consumer_application_id = $request->get('id');
                $files->file_type = 'cheque';
            } else {
                $files = new MerchantFiles();
                $files->merchant_id = $request->get('id');
                $files->file_type = 'cancelled_cheque';
            }
            $filePathSave = $filePath;
            if ((strpos($filePath, 'creditfair-customer-documents/') !== false)) {
                $filePathSave = str_replace('creditfair-customer-documents/', '', $filePath);
            }
            $files->file_path = $filePathSave;
            $files->save();
        }
        if ($filePath) {
            $request = new Request(['file' => $file, 'file_object' => true, 'type' => 'cheque', 'id' => $id]);
            $data = (new OCRRecognition($request))->get();
            $data['status'] = 'OK';
            if (isset($data['acc_no'])) {
                return response()->json($data, 200);
            }
        }
        return response()->json(['status' => 'FAIL'], 200);
    }

    public function uploadDocumentOnOCR($id, $request, $file, $type, $visibility = false)
    {
        $filePath = '';
        $file_path = '/' . $id . '/' . $type . '.' . $file->getClientOriginalExtension();

        if ($file_path) {
            if ($visibility && strpos($type, 'aadhar_card') !== false) {
                $s3 = Storage::disk('s3_temp');
            }else{
                $s3 = Storage::disk('s3');
            }
            //(new Slack(new Request(['title' => 'Before Uploading on s3', 'fields' => ['id' => $id,'filepath' => $file_path], 'group' => Slack::$STAGE_TESTING])))->send();
            $s3->put($file_path, $file);
            //(new Slack(new Request(['title' => 'After Uploading on s3', 'fields' => ['id' => $id,'filepath' => $file_path], 'group' => Slack::$STAGE_TESTING])))->send();
            $s3_path = $this->getUploadedFileName($s3, $file_path);
            //(new Slack(new Request(['title' => 'Path after Uploading', 'fields' => ['id' => $id,'filepath' => $s3_path], 'group' => Slack::$STAGE_TESTING])))->send();
            $this->uploadConsumerFiles($id, $type, $s3_path, $request);
            if ($visibility) {
                $s3->setVisibility($s3_path, OCRRecognition::PUBLIC);
                if(strpos($type, 'aadhar_card') !== false){
                    $filePath = 'https://'._env('AWS_TEMP_BUCKET')._env('AWS_ORIGIN') . '/' . $s3_path;
                }else{
                    $filePath = 'https://'._env('AWS_BUCKET')._env('AWS_ORIGIN') . '/' . $s3_path;
                }
            }else{
                $filePath = 'https://'._env('AWS_BUCKET')._env('AWS_ORIGIN') . '/' . $s3_path;
            }

        }
        return $filePath;
    }

    public function checkCurrentApplicationStatus(Request $request)
    {
        $status = 'OK';
        $data = [];
        if ($request->has('application_id')) {
            if (!$request->has('secondary_status') || !$request->get('secondary_status')) {
                $application = ConsumerApplication::where('id', $request->get('application_id'))
                    ->where('state', $request->get('status'))->first(['id', 'applicant_id', 'offer_id']);
            } else {
                $application = ConsumerApplication::where('id', $request->get('application_id'))
                    ->where('secondary_status', $request->get('secondary_status'))->first(['id', 'applicant_id', 'offer_id']);
            }
            if (isset($application->id) && (!$request->has('disbursement_page') || ($request->has('disbursement_page') && $request->get('disbursement_page') == 0))) {
                $status = 'FAIL';
            }

            $application = ConsumerApplication::with('merchant', 'application_element', 'application_element.merchant_center','emi','emi.offer','offer','proFormaInvoice','invoice')->where('id', $request->get('application_id'))->first(['id', 'merchant_id','name','approved_amount','offer_id','applicant_id','lender_id','co_applicant_name','purpose','tenure']);
            if (isset($application->id)) {
                if($request->get('status') == 'cf approved' && in_array($application->merchant_id , AvanseProcesses::activatedMerchants()) && $application->lender_id == AvanseServices::$lender_id){
                    new AvanseCreditPolicy(new PolicyAttributes(new Request(['id' => $request->get('application_id'), 'applicant_type' => 1])));
                    if(isset($application->co_applicant_name) && $application->co_applicant_name){
                        new AvanseCreditPolicy(new PolicyAttributes(new Request(['id' => $request->get('application_id'), 'applicant_type' => 2])));
                    }
                }

                if ($application->application_element && $application->application_element->merchant_center && $application->application_element->merchant_center->is_physical_verification == 1) {
                    $data['merchant']['physical_verification'] = ['message' => 'Physical verification is pending for center', 'status' => 1];
                } else if ($application->merchant && $application->merchant->is_physical_verification == 1) {
                    $data['merchant']['physical_verification'] = ['message' => 'Physical verification is pending for merchant', 'status' => 1];
                }

                //disbursement_data
                if($request->get('status') == 'disbursed') {
                    $data['disbursement_data'] = $this->getDisbursementSummary($request, $application);
                }
            }

            if($application->application_element && $application->application_element->payment_transfer_date) {
                $payment_transfer_date = ($application->application_element && $application->application_element->payment_transfer_date ? $application->application_element->payment_transfer_date : '');
                $data['payment_transfer_date'] = $payment_transfer_date;
            }

            $selected_lender = MerchantWhitelistLender::with('lender')->where('merchant_id', $application->merchant_id)->whereNull('deleted_at')->get(['id','lender_id']);
            $data['selected_lender'] = '';
            $lendersData = [];
            foreach($selected_lender as $_selected_lender) {
                if ($_selected_lender->lender->id && !in_array($_selected_lender->lender->id, $lendersData)) {
                    $selected = $_selected_lender->lender->id == 20 ? 'selected="selected"' : '';
                    if($request->get('status') == 'approved') {
                        $selected = $application->lender_id == $_selected_lender->lender->id ? 'selected="selected"' : '';
                    }
                    $data['selected_lender'] .= '<option '.$selected.' value="' . $_selected_lender->lender->id . '">' . $_selected_lender->lender->name . '</option>';
                    $lendersData[] = $_selected_lender->lender->id;
                }
            }
            if ($request->get('status') == 'approved') {
                // Example risk categories array (replace with actual data if different)
                $risk_categories = self::$risk_category;

                $data['risk_category'] = '';
                if($application->application_element->risk_category !== "W"){
                    unset($risk_categories["W"]);
                }
                // Iterate through risk categories to construct options
                foreach ($risk_categories as $key => $label) {
                    // Check if the current risk category matches the application's risk category
                    $selected = (isset($application->application_element->risk_category) &&
                                 $application->application_element->risk_category === $key)
                                ? 'selected="selected"'
                                : '';

                    // Append the option to the risk category data
                    $data['risk_category'] .= '<option ' . $selected . ' value="' . htmlspecialchars($key) . '">' . htmlspecialchars($label) . '</option>';
                }
            }
            $data['lender_id'] = $application->lender_id;
            $data['is_avanse_enabled'] = in_array($application->merchant_id , AvanseProcesses::activatedMerchants()) ? 1 : 0;
            $data['is_bnpl'] = $application->application_element->is_bnpl ? 1 : 0;

            $liabilityLog = LiabilityLog::where('application_id', $request->get('application_id'))->first(['liability_percent']);
            if(!isset($liabilityLog->liability_percent) || (isset($liabilityLog->liability_percent) && !$liabilityLog->liability_percent)){
                if($application->merchant && $application->merchant->liability_percent){
                    $data['liability_percent'] = $application->merchant->liability_percent;
                }
            }else{
                $data['liability_percent'] = $liabilityLog->liability_percent;
            }

            if($application->merchant && ($application->merchant->is_fldg_active || $application->merchant->hold_liability)){
                $FLDGCategory = FLDGCategory::where('merchant_id', $application->merchant->id)->get(['id','name','available_exposure']);
                /*if($application->merchant->available_exposure > 0) {*/ //(new FLDGController($request))->getAvailableExposure($application->merchant->id, $application->id)
                if($FLDGCategory) {
                    $data['FLDGCategory'] = '';
                    foreach ($FLDGCategory as $item) {
                        /*if ($item->available_exposure > 0) {*/
                            $data['FLDGCategory'] .= '<option value="' . $item->id . '">' . $item->name . '</option>';
                        /*}*/
                    }
                }
                /*}*/
            }
            $data['insurance_amount'] = 0;
            // $cat = _env('APP_CONNECTION') ? 24 : 6;
            // if($application->purpose == $cat){
            if(isset($application->proFormaInvoice->insurance_premium_applicable) && $application->proFormaInvoice->insurance_premium_applicable == 1){
                // cf discount value coming from consumer application
                // $discount_on_cf_charge = ($application->application_element->discount_by_cf)/100;
                // $discount_value = $discount_on_cf_charge != 0 ? (0.125/100)*$discount_on_cf_charge : (0.125/100);
                // // vendor discount
                // $discounted_loan_amount = round(($application->approved_amount * (0.125/100)),2);
                // $discounted_cf_amount = round(($application->approved_amount * $discount_value),2);
                // $agst = round($discounted_loan_amount * 0.18,2);
                // $cgst = round($discounted_cf_amount * 0.18,2);

                // $data['insurance_amount'] = $discounted_loan_amount + $discounted_cf_amount + $agst +$cgst;
                $processingFee = $application->emi->processing_fee ?? 0;
                $approvedLog = StatusLogs::where('application_id', $application->id)->where('status', 'approved')->orderBy('created_at', 'asc')->first(['created_at']);
                $approvedDate = null;
                if ($approvedLog) {
                    $approvedDate = Carbon::parse($approvedLog->created_at);
                }
                // $tenure_in_years = ceil($application->tenure / 12);
                $tenure_in_years = $application->proFormaInvoice->insurance_coverage ? $application->proFormaInvoice->insurance_coverage : 1;
                $data['insurance_coverage'] = $tenure_in_years;
                $data['insurance_amount'] = $this->insuranceCalculation($application->approved_amount, $application->application_element->discount_by_cf, $processingFee, 0, $tenure_in_years, $approvedDate, $application->application_element->inverter_gross_project_amount ?? 0, $application->id);
                if (is_null($data['insurance_amount'])) {
                    $status = 'FAIL';
                    $data['error'] = 'Gross project amount is mandatory for new cases but was missing or invalid.';
                }
                $data['discount_by_cf'] = $application->application_element->discount_by_cf ?? 0;
            }

            $data['decision_reason'] = '';
            $decision_reason_list = $this->decision_reason_list;
            foreach ($decision_reason_list as $drl_index => $reason) {
                $selected = $drl_index == $application->application_element->decision_reason ? "selected='selected'" : '';
                $data['decision_reason'] .= '<option '.$selected.' value="' . $drl_index . '">' . $reason . '</option>';
            }

            $data['decision_reason_other'] = $application->application_element->decision_reason_other;
        }

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

    public function calculateInsurance(Request $request)
    {
        $loan_amount = $request->input('loan_amount');
        $gross_project_amount = $request->input('gross_project_amount', 0); //For fronted request update the profroma
        $discount = $request->input('discount', 0);
        $id = $request->input('id', 0);
        $pf = $request->input('pf', 0);
        $split = $request->input('split', 0);


        if ($id == 0) {
            return response()->json([
                'success' => false,
                'message' => 'Invalid application ID.',
            ], 400);
        }

        $approvedDate = $request->input('approvedDate') ? Carbon::parse($request->input('approvedDate')) : null;

        $approvedLog = StatusLogs::where('application_id', $id)
            ->where('status', 'approved')
            ->orderBy('created_at', 'asc')
            ->first(['created_at']);

        if ($approvedLog) {
            $approvedDate = Carbon::parse($approvedLog->created_at);
        }

        //$tenureData = ConsumerApplication::where('id', $id)->first(['tenure']);
        //$tenure_in_months = $tenureData ? $tenureData->tenure : 0;
        $proFormaInvoice = ProFormaInvoice::where('application_id', $id)->first(['id','insurance_coverage']);
        $application_element = ConsumerApplicationElement::where('application_id', $id)->first(['type_of_customer', 'inverter_gross_project_amount']);
        $tenure_in_years = isset($proFormaInvoice->insurance_coverage) && $proFormaInvoice->insurance_coverage ? $proFormaInvoice->insurance_coverage : (isset($application_element->type_of_customer) && in_array($application_element->type_of_customer, [1,5]) ? 5 : 1);
        $tenure_in_years = $request->input('tenure_in_years') > 0 ? $request->input('tenure_in_years') : $tenure_in_years;

        if (empty($gross_project_amount) && isset($application_element->inverter_gross_project_amount)) {
            $gross_project_amount = $application_element->inverter_gross_project_amount;
        }

        $insuranceAmount = $this->insuranceCalculation($loan_amount, $discount, $pf, $split, $tenure_in_years, $approvedDate, $gross_project_amount, $id);
        if ($insuranceAmount === null) {
            return response()->json([
                'success' => false,
                'message' => 'Gross project amount is mandatory for new cases but was missing or invalid.',
            ], 400);
        }

        if ($insuranceAmount !== null) {
            $application = ConsumerApplication::where('id', $id)->first(['merchant_id']);
            if(isset($application->merchant_id)) {
                $merchant = Merchant::where('id', $application->merchant_id)->first(['insurance_premium','insurance_collection_method']);
                $existingInvoice = ProFormaInvoice::where('application_id', $id)->first(['insurance_premium_applicable', 'insurance_premium_by_merchant']);
                
                ProFormaInvoice::updateOrCreate(
                    ['application_id' => $id],
                    [
                        'insurance_premium_applicable' => isset($existingInvoice->insurance_premium_applicable) ? $existingInvoice->insurance_premium_applicable : $merchant->insurance_premium,
                        'insurance_premium_amount' => $insuranceAmount,
                        'insurance_premium_by_merchant' => isset($existingInvoice->insurance_premium_by_merchant) ? $existingInvoice->insurance_premium_by_merchant : $merchant->insurance_collection_method,
                        'insurance_coverage' => (int)$tenure_in_years,
                    ]
                );
            }
        }

        return response()->json([
            'success' => true,
            'message' => 'Insurance amount calculated successfully.',
            'insurance_amount' => $insuranceAmount,
            'tenure_in_years' => $tenure_in_years,
        ]);
    }


    public function insuranceCalculation($loan_amount, $discount, $pf, $split = 0, $tenure_in_years = 1, $approvedDate = null, $gross_project_amount = 0, $application_id = null)
    {
        // Parse the release dates
        $insuranceNewCalculationReleaseDate = Carbon::parse($this->releaseDates['insurance_new_calculation']);
        $insuranceGrossCalculationReleaseDate = Carbon::parse($this->releaseDates['insurance_gross_calculation']);

        // Determine which base amount to use based on the new gross project amount logic
        $isGrossProjectMandatory = empty($approvedDate) || Carbon::parse($approvedDate)->gte($insuranceGrossCalculationReleaseDate);
        $Loan_amount_Flag = true;

        if ($isGrossProjectMandatory) {
            if (empty($gross_project_amount) || $gross_project_amount <= 0) {
                $cwFactory = new CloudWatchLoggerFactory();
                $cwFactory->logger(json_encode([
                    'title'           => 'Insurance Calculation Failed',
                    'application_id'  => $application_id ?? 'Unknown',
                    'reason'          => 'Gross project amount is mandatory for new cases but was missing or invalid',
                    'amount_provided' => empty($gross_project_amount) ? 'empty' : $gross_project_amount,
                ]));
                return 0;
            }
            $base_amount = $gross_project_amount;
            $Loan_amount_Flag = false;
        } else {
            $base_amount = $loan_amount;
        }

        // Check if the approved date exists and is before the new calculation release date
        if (isset($approvedDate) && $insuranceNewCalculationReleaseDate->gt($approvedDate)) {
            // Calculate discount on CF charge as a fraction
            $discount_on_cf_charge = ($discount) / 100;

            // Determine the discount value based on the discount percentage
            $discount_value = $discount_on_cf_charge != 0 ? (0.125 / 100) * $discount_on_cf_charge : (0.125 / 100);

            // Calculate the vendor insurance part (0.125% of the base amount)
            $vendor_insurance_part = round(($base_amount * (0.125 / 100)), 2);

            // Calculate the CF insurance part after applying discount
            $discounted_cf_amount = round(($base_amount * $discount_value), 2);

            // GST calculations for both vendor and CF insurance parts (18% GST)
            $vender_gst = round($vendor_insurance_part * 0.18, 2);
            $cf_gst = round($discounted_cf_amount * 0.18, 2);

            // Add GST to get final amounts
            $vendor_insurance_part_with_gst = $vendor_insurance_part + $vender_gst;
            $cf_insurance_part_with_gst = $discounted_cf_amount + $cf_gst;

            // Calculate the total insurance amount (sum of all components)
            $total_insurance = $vendor_insurance_part + $discounted_cf_amount + $vender_gst + $cf_gst;

        } else {
            // Apply discount on CF charge as a fraction
            $discount_on_cf_charge = ($discount) / 100;

            // Ensure a minimum base amount of 100,000 for insurance calculation
            if ($Loan_amount_Flag) {
                $base_amount = ($base_amount <= 100000) ? 100000 : $base_amount;
            }

            // Define premium rate (0.15% per year)
            $premium_rate = 0.15 / 100;

            // Calculate vendor and CF insurance parts based on tenure in years
            $vendor_insurance_part = $premium_rate * $base_amount * $tenure_in_years;
            $cf_insurance_part = $premium_rate * $base_amount * $tenure_in_years;

            // Apply discount to CF insurance part if applicable
            $discount_amount = (isset($discount) && $discount >= 0 && $discount <= 100) ? $cf_insurance_part * ($discount / 100) : 0;
            $cf_insurance_part_with_discount = $cf_insurance_part - $discount_amount;

            // Add GST (18%) to both vendor and CF insurance parts
            $vendor_insurance_part_with_gst = $vendor_insurance_part + ($vendor_insurance_part * 0.18);
            $cf_insurance_part_with_gst = $cf_insurance_part_with_discount + ($cf_insurance_part_with_discount * 0.18);

            // Calculate total insurance cost
            $total_insurance = $vendor_insurance_part_with_gst + $cf_insurance_part_with_gst;
        }

        // If split is enabled, return detailed breakdown of insurance costs
        if ($split) {
            $amount['insurnace_permium'] = $vendor_insurance_part_with_gst;
            $amount['cf_insurance_processing_fees'] = $cf_insurance_part_with_gst;
            $amount['processing_fee'] = $pf;
            $amount['total'] = round($total_insurance);
            return $amount;
        }
        // Return total insurance amount rounded to the nearest whole number
        return round($total_insurance);
    }

    public function getDisbursementSummary(Request $request, $application){
        $data = [];
        $disbursement = (new DisbursementController($request))->getDisbursementAmount($application);

        $multiStageDisbursement = new MultiStageDisbursement();
        if ($multiStageDisbursement->canPartialDisbursement($application->emi->offer->id, $application)) {
            if ($multiStageDisbursementData = $multiStageDisbursement->initPartialDisbursement($application, ['invoice' => $application->invoice])) {
                if (!is_bool($multiStageDisbursementData)) {
                    $disbursement['net_disbursement'] = $multiStageDisbursementData;
                }
            }
        }

        if (isset($disbursement['net_disbursement'])){
            $data['net_disbursement'] = $disbursement['net_disbursement'];
        }

        $data['withhold'] = 0;
        if($application->application_element && $application->application_element->hold_amount) {
            $withhold = ($application->application_element && $application->application_element->hold_amount ? $application->application_element->hold_amount : 0);
            $data['withhold'] = $withhold;
        }
        if($application->application_element && $application->application_element->payment_transfer_date) {
            $payment_transfer_date = ($application->application_element && $application->application_element->payment_transfer_date ? $application->application_element->payment_transfer_date : '');
            $data['payment_transfer_date'] = $payment_transfer_date;
        }
        if($application->application_element && empty($application->application_element->product_name)) {
            $data['product_name'] = '';
        }
        $data['is_payout'] = $application->application_element && $application->application_element->is_payout ? $application->application_element->is_payout : 0;
        $data['can_use_payout'] = 1;

        if(_env('payout') == 'paytm') {
            if (!(new PayoutAPI($request))->prepare()->can_disbursed) {
                $data['can_use_payout'] = 0;
            }
        }
        if(!$this->getBankAccountDetails($application)){
            $data['can_use_payout'] = 0;
        }
        if(_env('payout') == 'paytm') {
            $walletConfiguration = WalletConfiguration::first();
            if (!isset($walletConfiguration->id)) {
                $data['can_use_payout'] = 0;
            }
        }
        if(isset($data['net_disbursement']) && $this->isTradeAdvanceApplicable($application, $data)){
            $data['can_use_payout'] = 0;
        }

        // if ((new AvanseProcesses(new Request(['id' => $application->id])))->checkEligibility() && $application->lender_id == AvanseServices::$lender_id){
        //     $data['can_use_payout'] = 0;
        // }

        if(!in_array($application->lender_id, [2,20])){
            $data['can_use_payout'] = 0;
        }

        return $data;
    }

    public function isTradeAdvanceApplicable($application, $data){
        if(isset($application->merchant->is_trade_advance) && $application->merchant->is_trade_advance == 1 && $application->merchant->trade_advance_amount > 0){
            if(($application->merchant->trade_advance_amount - $application->merchant->trade_advance_balance) > $data['net_disbursement']) {
                return true;
            }
        }

        return false;
    }

    public function getScoreCard(Request $request)
    {
        ConsumerApplication::$isCFFoirNotInclude = true;
        $scoreCard = new ScoreCard($request);
        $scoreCard->updateLoanStatus($request->get('application_id'));
        $application = ConsumerApplication::with('creditReport', 'foir', 'merchant.offer', 'application_element', 'emi')->where('id', $request->get('application_id'))->first();
        if ($error = $this->validateRequest($application)) {
            //return $error;
        }
        $scoreCard->setApplication($application);
        $data = $scoreCard->getScore();
        $data['error'] = $error;
        return $data;
    }

    public function refreshScoreCardData($application_id){
        ConsumerApplication::$isCFFoirNotInclude = true;
        $scoreCard = new ScoreCard(new Request());
        $scoreCard->updateLoanStatus($application_id);
        $application = ConsumerApplication::with('creditReport', 'foir', 'merchant.offer', 'application_element', 'emi')->where('id', $application_id)->first();
        $scoreCard->setApplication($application);
        $scoreCard->getScore();
    }

    public function DisbursedDataToBeFixed()
    {

        $jobs = JobProvider::where('available_at', Carbon::now()->toDateString())->get();

        $ids = [];
        foreach ($jobs as $job) {
            $ids[] = $job->application_id;
        }

        $applications = ConsumerApplication::with('emi', 'proFormaInvoice', 'bank_details')->whereIn('id', $ids)->where('state', 'disbursed')->whereNull('is_deleted')->get();

        $missing = [];
        foreach ($applications as $application) {
            if (empty($application->emi) || empty($application->proFormaInvoice) || empty($application->bank_details)) {
                $missing[] = [
                    'name' => $application->name,
                    'emi' => is_null($application->emi) ? 'Generate EMI' : '',
                    'proFormaInvoice' => is_null($application->proFormaInvoice) ? 'Generate PerForma' : '',
                    'bank' => is_null($application->bank_details) ? 'Bank Is Missing' : ''
                ];
            }
        }
        return (new CSV())->download($missing, 'missing_files');
    }

    public function getDataToBeFixed()
    {
        $applications = ConsumerApplication::whereNull('is_deleted')->get();

        foreach ($applications as $application) {
            $stateModel = StateModel::where('name', $application->current_address_state)->first(['code']);
            $view = array(
                'application_id' => $application->id,
                'applicant_type' => 0,
                'purpose' => '05',
                'name' => $application->name,
                'dob' => $application->dob,
                'pan_card' => $application->pan_card,
                'address' => $application->current_address_line_1 . ' ' . $application->current_address_state . ' ' . $application->current_address_city,
                'state' => isset($stateModel->code) ? $stateModel->code : '',
                'postal_code' => $application->current_address_pincode,
                'mobile_number' => $application->mobile_number
            );

            if (empty($application->current_address_pincode) || empty($application->pan_card) || ($application->dob == '1970-01-01') || !isset($stateModel->code)) {
                $missing[] = $view;
            } else {
                $data[] = $view;
            }
        }

        return (new CSV())->download($missing, 'missing_files');
    }

    public function sudoMvReport($id, $applicant_type)
    {
        try {
            $this->isInternal = true;
            //pan validation file
            $panData = $this->getPanValidation($id, $applicant_type);
            if (false !== $panData && isset($panData['report_data']['sch:ReportData']['sch:nsdlResponse'])) {
                if ($panData['report_data']['sch:ReportData']['sch:nsdlResponse']['sch:returnCode'] != "E") {
                    $fileName =  $id.'/'.$id;
                    $applicant_type = ($applicant_type == 1) ? '' : '_' . $applicant_type;
                    $file_path = "_response_pan_valid'.$applicant_type.'.json";
                    //shell_exec('mv ' . $fileName . $file_path . ' ' . $fileName . '_response_pan_valid_' . time() . '_old.json');
                    $old_path = $fileName . $file_path;
                    $new_path = $fileName . '_response_pan_valid_' . time() . '_old.json';
                    Equifax::moveFile($old_path, $new_path);
                }
            }else if(false !== $panData && isset($panData['kycResult'])){
                if($panData['kycResult']['idStatus'] != 'VALID'){
                    $fileName =  $id.'/'.$id;
                    $applicant_type = ($applicant_type == 1) ? '' : '_' . $applicant_type;
                    $file_path = "_response_pan_valid_decentro'.$applicant_type.'.json";
                    //shell_exec('mv ' . $fileName . $file_path . ' ' . $fileName . '_response_pan_valid_decentro_' . time() . '_old.json');
                    $old_path = $fileName . $file_path;
                    $new_path = $fileName . '_response_pan_valid_decentro_' . time() . '_old.json';
                    Equifax::moveFile($old_path, $new_path);
                }
            }

            //cibil report file
            $data = $this->getCibilReport($id, $applicant_type, '');
            if (!$data instanceof RedirectResponse) {
                if ((isset($data['report_data']['sch:ReportData']['sch:Error'])) || isset($data['error'])) {
                    if ((isset($data['report_data']['sch:ReportData']['sch:Error']['sch:ErrorCode'])) || (isset($data['error']) && $data['error'])) {
                        $fileName = $id.'/'.$id;
                        $applicant_type = ($applicant_type == 1) ? '' : '_' . $applicant_type;
                        //shell_exec('mv ' . $fileName . '_response' . $applicant_type . '.json' . ' ' . $fileName . '_response_' . time() . '_old.json');
                        $old_path = $fileName . '_response' . $applicant_type . '.json';
                        $new_path = $fileName . '_response_' . time() . '_old.json';
                        Equifax::moveFile($old_path, $new_path);
                    }
                }
            }
            return false;
        } catch (\Exception $e) {
            return false;
        }
    }

    public function generateCibilReport($id){
        $process = new AvanseProcesses(new Request());
        return $process->getCibilReport($id);
    }

    public function generateEqifaxReport($id, $type = 'customer', $only_bureau = false)
    {
        $applicant_type = Input::has('applicant_type') ? Input::get('applicant_type') : 1;
        $panVendor = '';
        if ($type == 'merchant') {
            $merchant = Merchant::find($id);

            $application = new \stdClass();
            $application->name = $merchant->owner_name;
            $application->gender = $merchant->gender;
            $application->dob = date('Y-m-d', strtotime($merchant->dob));
            $application->pan_card = $merchant->pan_card;
            $application->mobile_number = $merchant->contact_number;
            $application->loan_amount = 0;
            $address_line1 = $merchant->address;
            $address_state = $merchant->state;
            $address_city = $merchant->city;
            $address_pincode = $merchant->pincode;

            $stateModel = StateModel::where('name', $address_state)->first(['code', 'code_number']);
        } else {
            $applicationData = ConsumerApplication::find($id);
            $consent_type = ($applicant_type == 1) ? "consent_logs" : "co_app_consent_logs";
            $consumerFiles = ConsumerApplicationFiles::where([
                ['consumer_application_id', $id],
                ['file_type', $consent_type],
                ['applicant_type', $applicant_type]
            ])->first();
            
            if (!$consumerFiles) {
                $consentErr = ($applicant_type == 1) ? "Applicant consent missing" : "CO-Applicant consent missing";
                return ['status' => 'FAIL', 'message' => $consentErr];
            }
            

            //ID - 1646 Conditions
            if(!$this->isRoot) {

                if (isset($applicationData->merchant_id) && in_array($applicationData->merchant_id, [4438, 4439, 4446, 4440, 4437, 73])) {
                    return false;
                }

                if(isset($applicationData->merchant_id) && $applicationData->merchant_id){
                    $isCheck = Merchant::where('id', $applicationData->merchant_id)->where('is_guest_active', 0)->first(['id']);
                    if((isset($isCheck->id) || $applicationData->merchant_id == 21) && $applicationData->employee_status != 'SALARIED' && empty($applicationData->company_name)){
                        return false;
                    }
                }
            }
            //End


            $this->sudoMvReport($id, $applicant_type);

            if ($applicant_type == 1) {
                if (isset($applicationData->permanent_address_line_1) && $applicationData->permanent_address_line_1 != "") {
                    $address_line1 = $applicationData->permanent_address_line_1;
                    $address_state = $applicationData->permanent_address_state;
                    $address_city = $applicationData->permanent_address_city;
                    $address_pincode = $applicationData->permanent_address_pincode;
                } else {
                    $address_line1 = $applicationData->current_address_line_1;
                    $address_state = $applicationData->current_address_state;
                    $address_city = $applicationData->current_address_city;
                    $address_pincode = $applicationData->current_address_pincode;
                }
                $application = $applicationData;
                $stateModel = StateModel::where('name', $address_state)->first(['code', 'code_number']);
            } else {
                $address_line1 = $applicationData->co_applicant_address_line_1;
                $address_state = $applicationData->co_applicant_address_state;
                $address_city = $applicationData->co_applicant_address_city;
                $address_pincode = $applicationData->co_applicant_address_pincode;
                $stateModel = StateModel::where('name', $address_state)->first(['code', 'code_number']);

                $application = new \stdClass();
                $application->name = $applicationData->co_applicant_name;
                $application->dob = date('Y-m-d', strtotime($applicationData->co_applicant_dob));
                $application->pan_card = $applicationData->co_applicant_pan_card;
                $application->mobile_number = $applicationData->co_applicant_mobile_number;
                $application->gender = $applicationData->co_applicant_gender;
                $application->loan_amount = $applicationData->loan_amount;
            }
        }

        $message = '';
        if (empty($application->name)) {
            $message = 'Name';
        }
        if (empty($application->dob)) {
            $message = 'Date of Birth';
        }
        if (empty($application->pan_card)) {
            $message = 'Pan Card';
        }
        if (empty($address_line1)) {
            $message = 'Address';
        }
        if (strlen($address_line1) >= 200) {
            $message = 'Address_length';
        }
        if (empty($address_state)) {
            $message = 'State';
        }
        if (empty($address_city)) {
            $message = 'city';
        }
        if (empty($address_pincode)) {
            $message = 'Pin code';
        }
        if (empty($application->mobile_number)) {
            $message = 'Mobile Number';
        }
        if ($type != 'merchant' && $applicant_type == 1 && !$only_bureau && empty($application->employee_status)) {
            $message = 'Employment detail';
        }

        if (!empty($message)) {
            if($only_bureau){
                $message = 'Bureau not pulled successfully because '. $message .' is missing in application.';
            }elseif($message == 'Address_length'){
                $message = 'Please check the address length';
            }else{
                $message .= ' is missing in application';
            }

            return ['status' => 'FAIL', 'message' => $message];
        }

        $_code_number = $stateModel->code_number ?? '';
        if($_code_number && strlen($_code_number) == 1){
            $_code_number = '0'.$_code_number;
        }

        $experian_data = array(
            'id' => (int)$id,
            'user_id' => 0,
            'applicant_type' => (int) $applicant_type,
            'first_name' => $application->name,
            'last_name' => substr($application->name, strrpos($application->name, ' ') + 1),
            'gender' => $application->gender == 'MALE' ? 1 : 2,
            'pan' => $application->pan_card,
            'amount' => (int)$application->loan_amount,
            'dob' => $application->dob,
            'pincode' => (int)$address_pincode,
            'city' => $address_city,
            'address' => $address_line1 . ' ' . $address_state . ' ' . $address_city,
            'state' => $_code_number ?? '',
            'district' => $address_city,
            'mobile'=> (int)$application->mobile_number,
            'request_type' => $type
        );
        $dataEquifax = ['applicant_type' => $applicant_type, 'application' => $application, 'address_line1' => $address_line1, 'address_state' => $address_state, 'address_city' => $address_city, 'stateModel' => $stateModel, 'address_pincode' => $address_pincode, 'type' => $type];
        $skip_pan_validation = (bool) (_env('SKIP_PAN_VALIDATION') ?? false);
        $panData = "";
        $panHttpCode = '';
        if(!$skip_pan_validation){
            $panData = $this->decentroPanValidaion($id,$dataEquifax['application']->pan_card);
            $panHttpCode = '';
            if($panData && is_object($panData)){
                $panHttpCode = $panData->httpcode;
            }else if($panData){
                $panHttpCode = $panData['httpcode'];
            }
        }
        if(!$skip_pan_validation && $panHttpCode == '' || (isset($panHttpCode) && $panHttpCode != 200 && isset($panData->status) && $panData->status != "SUCCESS" && $panHttpCode != null)){
            // $panData = $this->runPanValidation($id, $dataEquifax);
            // $panVendor = 'equifax';
        }else {
            $panVendor = 'decentro';
            if ($panData) {
                if ($type == 'merchant') {
                    $filePath = '/merchant/' . $id . '/' . $id . "_response_pan_valid_decentro_merchant.json";
                } else {
                    $applicant_type_v1 = ($applicant_type == 1) ? '' : '_' . $applicant_type;
                    $filePath = $id . '/' . $id . "_response_pan_valid_decentro" . $applicant_type_v1 . ".json";
                }
                $s3 = Storage::disk('s3');
                $s3->put($filePath, json_encode($panData));
            }

            if ($skip_pan_validation || $panData) {
                $experian_data['panVendor'] = $panVendor;
                // for education
                if($type != 'merchant' && in_array($applicationData->purpose,[4,33,34,35,36])){
                    $experian_data['ex_purpose'] = '27';
                }
                $pan_data = array('panValidation' => wall_encrypt(json_encode($panData)));
                $bureau_data = array_merge($experian_data, $pan_data);
                if (_env('APP_DEBUG') == 1){ //  for testing on staging
                    $getResponse = 'success';
                } else {
                    $getResponse = $this->runExperian($bureau_data, $panData);
                }
            }
            if (isset($getResponse) && $getResponse == 'success') {
                if ($applicant_type == 2) {
                    $grade = new GradeController(new Request());
                    $grade->autoApproveInitCoapplicant($id);
                }
                return ['status' => 'OK', 'message' => 'Experian Report Generated Successfully'];
            } else if (isset($panData) && isset($getResponse) && strlen($getResponse) && is_string($getResponse) && $getResponse != 'Internal server error' && strpos($getResponse, "SYS00601") !== true) {
                if($getResponse == 'SYS100004  (No record found)'){
                    $creditReport = CreditReport::where('application_id', $experian_data['id'])->where('applicant_type', $experian_data['applicant_type'])->first(['id']);
                    if (isset($creditReport->id)) {
                        $creditReport = CreditReport::find($creditReport->id);
                    } else {
                        $creditReport = new CreditReport();
                    }
                    $applicant_type_v2 = ($applicant_type == 1) ? '' : '_' . $applicant_type;
                    $s3_bureau_filepath = $experian_data['id'].'/'. $experian_data['id'].'_response'.$applicant_type_v2.'_experian.json';
                    $eqfx = new Equifax(new Request());
                    $burea_data_s3 = $eqfx->getData($s3_bureau_filepath);
                    $creditReport->application_id = $experian_data['id'];
                    $creditReport->bureau = 'experian';
                    $creditReport->applicant_type = $applicant_type;
                    $creditReport->panValidation = json_encode($panData);
                    $creditReport->panVendor = $experian_data['panVendor'];
                    $creditReport->Score = $burea_data_s3['Body']['ProcessResponse']['Out']['INProfileResponse']['SCORE']['BureauScore'];
                    $creditReport->created_at = Carbon::now()->toDateTimeString();
                    $creditReport->save();
                    if ($applicant_type == 2) {
                        $grade = new GradeController(new Request());
                        $grade->autoApproveInitCoapplicant($id);
                    }
                    return ['status' => 'OK', 'message' => 'New to Credit Case'];
                }
            } else {
                $dataEquifax['panVendor'] = $panVendor;
                // for education
                if($type != 'merchant' && in_array($applicationData->purpose,[4,33,34,35,36])){
                    $dataEquifax['Eq_purpose'] = '08';
                }
                $callEquifax = $this->callEquifax($id, $dataEquifax);
                $sendResponse = $callEquifax['sendResponse'];
                $error_msg = $callEquifax['error_msg'];
                $response = $callEquifax['response'];
                if (empty($sendResponse)) {
                    $error_msg = $only_bureau ? 'Bureau not pulled successfully because something went wrong' : 'Something went wrong';
                } else if (is_string($sendResponse)) {
                    $error_msg = ($response) ? ($only_bureau ? 'Bureau not pulled successfully - ' . $response : $response) : ($only_bureau ? 'Bureau not pulled successfully because something went wrong' : 'Something went wrong');
                }

                $equifaxRequest = new Equifax(new Request(array("application_id" => $id, "applicant_type" => $applicant_type, "request_type" => $type, 'error_check' => true)));
                $response = $equifaxRequest->parseResponse();
                if ($response) {
                    $errorString = ['status' => 'FAIL', 'message' => $only_bureau ? 'Bureau not pulled successfully because ' . $response : $response];
                }

                if (isset($error_msg) && $error_msg && $error_msg != 'Consumer record not found') {
                    return ['status' => 'FAIL', 'message' => $error_msg . '. Please check this information
                    1. Name
                    2. Date of Birth
                    3. Pan number with original one`
                    4. Address: Pincode and State
                    5. Gender'
                    ];
                } elseif (isset($errorString) && $errorString['message'] != 'Consumer record not found') {
                    return $errorString;
                } else {
                    if ($type == 'merchant') {
                        $this->isInternal = true;
                        $data = $this->getCibilReport($id, $applicant_type, '_' . $type);
                        $view = view('front.cibil-report', $data);
                        $pdf = App::make('snappy.pdf.wrapper');
                        $equifax_report = $pdf->loadHTML($view);
                        $document = new ConsumerDocument(new Request());
                        $document->isMerchantRequest = 1;
                        $document->uploadToS3('equifax_report', $id, $equifax_report->output());
                    } else {
                        $equifax = new Equifax(new Request(array("application_id" => $id, "applicant_type" => $applicant_type, "request_type" => $type, 'panVendor' => $panVendor)));
                        $response = $equifax->parseResponse()->setRecord();

                        if ($response->error != "") {
                            return ['status' => 'FAIL', 'message' => $only_bureau ? 'Bureau not pulled successfully because ' . $response->error : $response->error];
                        }
                        if ($only_bureau) {
                            if ($applicant_type == 2) {
                                $grade = new GradeController(new Request());
                                $grade->autoApproveInitCoapplicant($id);
                            }
                            return ['status' => 'OK', 'message' => 'Equifax Report Generated Successfully'];
                        }
                    }
                    return ['status' => 'OK', 'message' => 'Equifax Report Generated Successfully'];
                }
            }
        }
    }

    public function runAutoDecision($id, $type=null, $account_aggregator_id=null){
        $request = new Request();
        $request->attributes->add(['application_id' => $id]);

        if (in_array($type, ['banking_decision_webhook', 'cf_banking_decision_webhook'])) {
            $request->attributes->add(['skip_auto_reject' => true]); 
            $request->attributes->add(['rule_filter' => 'emi_multiplier_on_abb']);
        }

        if ($account_aggregator_id) {
            $request->attributes->add(['account_aggregator_id' => $account_aggregator_id]);
        }

        $this->getScoreCard($request);
        
        $gradeStatus = $this->runAutoDecisionAlgorithm($request, $id);
        $isApproved = 0;
        $isRejected = isset($gradeStatus->rejected_case) ? 1 : 0;
        if ($gradeStatus instanceof \Illuminate\Http\Response) {
            $responseData = json_decode($gradeStatus->getContent());
        }
        $isPreApproved = isset($responseData->pre_approved) ? 1 : 0;
        if (isset($gradeStatus->auto_approved)) {
            $isApproved = 1;
        }
        if ($isApproved == 1 && !in_array($type, ['autoBRE', 'cf_banking_decision_webhook'])) {
            (new Slack(new Request(['title' => 'Run Auto Decision function', 'fields' => ['type' => $type, 'isApproved' => $isApproved], 'group' => Slack::$STAGE_TESTING])))->send();
            $application = ConsumerApplication::where('id', $id)->first(['id', 'merchant_id']);
            $status = 'approved';
            if ($this->isMultiLender($application->merchant_id) > 1) {
                $status = 'cf approved';
            }
            Input::merge(['state' => $status]);
            $this->auto_approved_status = true;
            $this->updateApplicationStatus($id, $status);
        }
        $this->gradeStatusAutoDecision = $gradeStatus;

        return ['isApproved' => $isApproved, 'isRejected' => $isRejected, 'isPreApproved' => $isPreApproved];
    }

    public function runPanValidation($id, $dataEquifax){
        $data = $this->callEquifax($id, array_merge($dataEquifax, ['only_pan' => 1]));
        return (new Equifax(new Request(['applicant_type' => $dataEquifax['applicant_type'], 'application_id' => $id])))->getPanValidationData($data);
    }

    public function decentroPanValidaion($id, $pan){
        $wrapper = new Wrapper();
        $wrapperMethods = $wrapper->register(DecentroMethods::class);
        $wrapper->payload->addPayload(new Request(['id' => $id,'pan'=>$pan]));
        $wrapperRes = $wrapperMethods->validate($wrapper);
        if(!isset($wrapperRes->kycStatus) || $wrapperRes->kycStatus == "FAILURE"){
            try {
                $comment = new Comments();
                $comment->application_id = $id;
                $comment->user_id = 107;
                $comment->comment = 'PAN validation failed using Decentro. PAN Number - '.$pan;
                $comment->show_merchant = 0;
                $comment->show_consumer = 0;
                $comment->save();
            } catch (\Exception $e) {
                // preserve original validation failure handling even if comment save fails
            }
            return null;
        }

        return $wrapperRes;

    }

    private function callEquifax($id, $data){
        $equifax_data = array(
            'application_id' => $id,
            'applicant_type' => $data['applicant_type'],
            'purpose' => isset($data['Eq_purpose']) ? $data['Eq_purpose'] : '05',
            'name' => trim($data['application']->name),
            'dob' => $data['application']->dob,
            'pan_card' => $data['application']->pan_card,
            'address' => str_replace("&", "", $data['address_line1'] . ' ' . $data['address_state'] . ' ' . $data['address_city']),
            'state' => $data['stateModel']->code ?? '',
            'postal_code' => $data['address_pincode'],
            'mobile_number' => $data['application']->mobile_number,
            'request_type' => $data['type']
        );

        if (isset($data['only_pan'])){
            $equifax_data['only_pan'] = 1;
        }

        $payload = json_encode($equifax_data);
        //return ['status'=>'OK','message'=>$payload];
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => _env('EQUIFAX_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,
            CURLOPT_HTTPHEADER => array(
                "Content-Type: application/json",
            ),
        ));

        $response = curl_exec($curl);
        $sendResponse = json_decode($response);
        if (curl_error($curl)) {
            $error_msg = curl_error($curl);
        }
        curl_close($curl);
        $cwFactory = new CloudWatchLoggerFactory();
        $data = array('application_id'=>$id, 'user_id'=> isset(Auth::user()->id)? Auth::user()->id : '', 'vendor'=> 'equifax', 'api_name'=> 'pan validation and bureau data', 'api_url' => _env('EQUIFAX_URL'),'Request'=> $equifax_data, 'Response'=>$sendResponse, 'error_msg' => isset($error_msg) ? $error_msg : '');
        $cwFactory->logger(json_encode($data));
        return ['sendResponse' => $sendResponse, 'error_msg' => $error_msg ?? '', 'response' => $response];
    }

    public function runExperian($experian_data, $panData = false){
//        $payload = http_build_query($experian_data);
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => _env('EXPERIAN_URL'), //'192.168.29.203:8060/experian', //https://amqnnsrsy5.execute-api.ap-south-1.amazonaws.com/Prod
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => json_encode($experian_data),
            CURLOPT_HTTPHEADER => array(
                "Content-Type: application/json",
            ),
        ));

        $response = curl_exec($curl);
        $sendResponse = json_decode($response);

        if (curl_error($curl)) {
            $error_msg = curl_error($curl);
        }
        $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

        curl_close($curl);

//        if(isset($sendResponse->status) && isset($sendResponse->message) && $sendResponse->status == 'FAIL' && strpos($sendResponse->message, 'No record found') && $panData){
//            $creditReport = CreditReport::where('application_id', $experian_data['id'])->where('applicant_type', $experian_data['applicant_type'])->first(['id']);
//            if (isset($creditReport->id)) {
//                $creditReport = CreditReport::find($creditReport->id);
//            } else {
//                $creditReport = new CreditReport();
//            }
//
//            $creditReport->application_id = $experian_data['id'];
//            $creditReport->panValidation = json_encode($panData);
//            $creditReport->applicant_type = $experian_data['applicant_type'];
//            $creditReport->created_at = Carbon::now()->toDateTimeString();
//            $creditReport->save();
//        }

        if (empty($sendResponse) || is_string($sendResponse) ||
            (isset($sendResponse->message) && $sendResponse->message == 'Internal server error') ||
            (isset($sendResponse->status) && $sendResponse->status == 'FAIL')) {
            $error_msg = ($sendResponse->message ?? ($error_msg ?? 'Something went wrong'));
        }
        else if(isset($sendResponse->message) && $sendResponse->message == ""){
            $error_msg = 'Experian bureau pull failed with empty response';
        }
        else if(isset($httpcode) && $httpcode != 200){
            $error_msg = 'Experian bureau pull failed with http code '.$httpcode;
        }
        $cwFactory = new CloudWatchLoggerFactory();
        $data = array('application_id'=>$experian_data['id'], 'user_id'=> isset(Auth::user()->id)? Auth::user()->id : '', 'vendor'=> 'experian', 'api_name'=> 'pan validation and bureau data', 'api_url' => _env('EXPERIAN_URL'),'Request'=> $experian_data, 'Response'=>$sendResponse, 'error_msg' => isset($error_msg) ? $error_msg : '');
        $cwFactory->logger(json_encode($data));

        return $error_msg ?? 'success';
    }

    public function runAutoDecisionAlgorithm(Request $request, $id)
    {
        $consumerApplication = ConsumerApplication::with('application_element', 'proFormaInvoice')->where('id', $id)->first();

        try {
            if (!in_array($consumerApplication->state, ['aborted', 'rejected'])/* && $consumerApplication->application_element && $consumerApplication->proFormaInvoice && $consumerApplication->proFormaInvoice->loan_application_no*/) {
                $gradeController = new GradeController($request);
                $gradeStatus = false;
                if (in_array($consumerApplication->state, $this->statusreversearray['approved'])) {
                    (new Slack(new Request(['title' => 'Auto Decision: autoApproveInit', 'fields' => ['id' => $id,'state' => $consumerApplication->state], 'group' => Slack::$STAGE_TESTING])))->send();
                    $isLog = \request()->get('log_decision') && \request()->get('log_decision');
                    $gradeStatus = $gradeStatusOriginal = $gradeController->autoApproveInit($id, $isLog);
                    if ($gradeStatus instanceof Response) {
                        $gradeStatus = $gradeStatus->getContent();
                        $gradeStatus = json_decode($gradeStatus);
                    }
                }

                if (isset($gradeStatus->rejected_case)) {
                    return $gradeStatus;
                }

                if (isset($gradeStatus->auto_approved)) {
                    //$this->updateApplicationStatus($id, 'approved');
                    return $gradeStatus;
                } else if (in_array($consumerApplication->state, $this->statusreversearray['pre approved']) && $gradeController->pre_approvalCheck($gradeController, $id)) {
                    $document_rule_id = $gradeController->initAutoDocumentation($gradeController, $id, false);
                    $this->sendPreApprovalCommunication($id, $document_rule_id);
                    $this->sendAutoPreApprovalCommunication($id);
                    $consumer_application = ConsumerApplication::find($id);
                    $consumer_application->state = "pre approved";
                    $consumer_application->save();

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

                    \Session::flash('success', 'Application is pre approved');
                    return response(['pre_approved' => true], 200);
                } else {
                    if ($consumerApplication->application_element && !$consumerApplication->application_element->auto_document_rule_id) {
                        $gradeController->initAutoDocumentation($gradeController, $id);
                    }
                    return false; // move the case to waiting for decision in case the no TOF eligible offers found
                }
            }
        } catch (\Exception $e) {

        }
    }

    public function getAdviserApplication()
    {
        $whereNotIncluded = ['aborted', 'rejected', 'disbursed', 'nach registered', 'closed', 'cancelled', 'cancellation in-process'];
        $applications = ConsumerApplication::whereNotIn('state', $whereNotIncluded)
            ->where('created_by', '>', 0)
            ->groupBy('created_by')->select(DB::raw('GROUP_CONCAT(DISTINCT id) as ids'), 'created_by')->get();
        return $this->getReminderDataForAdviser($applications);

    }

    public function getReminderDataForAdviser($applications)
    {
        $applicationData = [];
        foreach ($applications as $application) {
            $response = [];
            $data = ConsumerApplication::with('merchant', 'comment')->whereIn('id', explode(',', $application->ids))->whereNull('is_deleted')->get();
            foreach ($data as $item) {
                if (isset($item->merchant->merchant_name)) {
                    $response[$item->merchant->merchant_name][] = [
                        'id' => $item->id,
                        'customer_name' => $item->name,
                        'status' => $item->state,
                        'phone' => $item->mobile_number,
                        'email' => $item->email,
                        'tenure' => $item->tenure,
                        'purpose' => $item->merchant->merchant_category->name,
                        'loan_amount' => $item->loan_amount,
                        'approved_amount' => $item->approved_amount,
                        'merchant_name' => $item->merchant->merchant_name,
                        'comment' => isset($item->comment[0]->comment) ? $item->comment[0]->comment : '',
                        'commented_at' => isset($item->comment[0]->created_at) ? $item->comment[0]->created_at : '',
                        'comment_by' => (isset($item->comment[0]->user_id)) ? User::where('id', $item->comment[0]->user_id)->first(['name'])->name : ''
                    ];
                }
            }

            $applicationData[] = [
                'adviser' => User::where('id', $application->created_by)->first(['name', 'email', 'mobile_number', 'user_type']),
                'applications' => $response,
                'flag' => count($response) > 0 ? true : false
            ];
        }
        return $applicationData;
    }

    public function showInvoices(Request $request)
    {
        $txt = '';
        $data['lenders'] = Lenders::all();

        $isZipExport = Input::has('is_zip_export') ? true : false;
        $isFileExport = Input::has('is_file_export') ? true : false;
        $responseData = [];
        $hasData = false;
        $from_date = ($request->has('from_date') && !empty($request->get('from_date'))) ? Carbon::createFromFormat('Y-m-d', $request->get('from_date'))->toDateString() : Carbon::now()->toDateString();
        $to_date = ($request->has('to_date') && !empty($request->get('to_date'))) ? Carbon::createFromFormat('Y-m-d', $request->get('to_date'))->toDateString() : Carbon::now()->toDateString();
        $invoice_date = ($request->has('invoice_date') && !empty($request->get('invoice_date'))) ? Carbon::createFromFormat('Y-m-d', $request->get('invoice_date'))->toDateString() : Carbon::now()->toDateString();
        $data['state_name'] = $request->get('state_name');
        $data['merchant_id'] = $request->get('merchant_id');


        $statusLogs = StatusLogs::where('status', 'disbursed')->where('created_at', '>=', $from_date . ' 00:00:00')->where('created_at', '<=', $to_date . ' 23:59:59')->where('is_reversed',0)->get(['application_id']);

        $applicationIds = [];
        foreach ($statusLogs as $statusLog){
            if(!in_array($statusLog->application_id, $applicationIds)) {
                $applicationIds[] = $statusLog->application_id;
            }
        }

        $applications = ConsumerApplication::with('merchant','application_element.merchant_center')->whereHas('logs', function ($query) use ($from_date, $to_date) {
            $query->where('status', 'disbursed')->where('created_at', '>=', $from_date . ' 00:00:00')->where('created_at', '<=', $to_date . ' 23:59:59')->where('is_reversed',0);
        })->with(['lender' => function ($query) {
            $query->select('id', 'name');
        }, 'invoices' => function ($query) {
            $query->select('application_id', 'invoice_id', 'net_amount', 'cgst', 'sgst', 'igst', 'type', 'phase_id');
        }, 'emi' => function ($query) {
            $query->select('application_id', 'processing_fee', 'subvention');
        }, 'documents' => function ($query) {
            $query->whereIn('file_type', ['Processing Fee Invoice', 'merchant_disbursed'])->orderBy('created_at', 'desc')->select('consumer_application_id', 'file_path', 'file_type');
        }, 'merchant' => function ($query) {
            $query->select('id', 'merchant_name', 'email', 'contact_number', 'state','gst_number');
        }]);
        if($data['merchant_id']){
            $applications = $applications->where('merchant_id',$data['merchant_id']);
        }
//        if($data['state_name']){
//            $applications = $applications->where('permanent_address_state',$data['state_name']);
//        }
        $applications = $applications->whereNull('is_deleted')->whereIn('id', $applicationIds)->get(['id', 'merchant_id', 'name', 'email', 'mobile_number', 'lender_id', 'current_address_state', 'permanent_address_state', 'approved_amount', 'state']);

        /*$sql = 'SELECT emi_calculation.processing_fee, lenders.name as lender_name,consumer_application.current_address_state,consumer_application.permanent_address_state,consumer_application.id,consumer_application.name,consumer_application.email,consumer_application.mobile_number,consumer_application.lender_id,invoices.invoice_id,invoices.amount,invoices.net_amount,invoices.igst,invoices.cgst,invoices.sgst,(select created_at from status_logs where status_logs.status = "disbursed" and status_logs.application_id = consumer_application.id limit 1) as Disbursed_date,(select consumer_application_files.file_path from consumer_application_files where consumer_application_files.consumer_application_id = consumer_application.id and consumer_application_files.file_type = "Processing Fee Invoice" order by id desc limit 1) as File from consumer_application left JOIN emi_calculation on emi_calculation.application_id = consumer_application.id left JOIN invoices on invoices.application_id = consumer_application.id left JOIN lenders on lenders.id = consumer_application.lender_id where ((select created_at from status_logs where status_logs.status = "disbursed" and status_logs.application_id = consumer_application.id limit 1) BETWEEN "'.$from_date.' 00:00:00" and "'.$to_date.' 23:59:59")';*/
        /*if(isset($data['lender_id']) && $data['lender_id'] != "" && $data['lender_id'] != 0){
            $sql.= ' and consumer_application.lender_id = '.$lender_id;
        }*/
        /*if($data['state_name']){
            $sql.= ' and consumer_application.permanent_address_state = "'.$data['state_name'].'"';
        }

        $type = 'processing_invoice';
        $sql.= ' and invoices.amount > 0 and consumer_application.is_deleted is Null order by Disbursed_date asc';

        $applications = DB::select($sql);*/

        if ($isZipExport) {
            $this->isInternal = true;
            $zip = new \ZipArchive();
            $zipFileName = storage_path().'/app/invoice_' . Carbon::now()->toDateTimeString() . '.zip';
            $res = $zip->open($zipFileName, \ZipArchive::CREATE);
        }

        $states = StateModel::all();
        $_states = [];
        $list = [];
        foreach ($states as $state){
            $_states[$state->name] = $state->code_number;
        }
        foreach ($applications as $application) {

            foreach ($application->invoices as $invoice) {

                $append = 1;
                $document = new ConsumerDocument($request);
                $process = null;
                $subvention_amount = 0;
                $response = array();

                if ($invoice->type != 'processing_invoice') {


                    $downPayment = 0;
                    if($application->merchant->charge_subvention_remaining_amount){
                        $downPayment = $application->emi->upfront_from_customer;
                    }


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

                    $process = $document->getGSTDetails(
                        [
                            'amount' => $subvention_amount,
                            'state' => $application->merchant->state
                        ], 0
                    );
                }

                $response['name'] = ($invoice->type != 'processing_invoice') ? $application->merchant->merchant_name : $application->name;
                $response['email'] = ($invoice->type != 'processing_invoice') ? $application->merchant->email : $application->email;
                $response['mobile_number'] = ($invoice->type != 'processing_invoice') ? $application->merchant->contact_number : $application->mobile_number;
                $response['lender_id'] = $application->lender_id;
                $response['application_id'] = $application->id;
                $response['amount'] = ($invoice->type == 'processing_invoice') ? $application->emi->processing_fee : 0;
                $response['net_amount'] = ($subvention_amount) ? $subvention_amount : $invoice->net_amount;
                $response['hide_row'] = !(in_array($application->state, ['disbursed', 'nach registered'])) ? 1 : 0;
                $response['status'] = $application->state;
                $response['gst_number'] = ($invoice->type != 'processing_invoice') ? (($application->application_element && $application->application_element->merchant_center && $application->application_element->merchant_center->gst_number) ? $application->application_element->merchant_center->gst_number : $application->merchant->gst_number) : '';
                $response['name_on_invoice'] = $invoice->type != 'processing_invoice' ? (($application->application_element && $application->application_element->merchant_center && $application->application_element->merchant_center->gst_number) ? $application->application_element->merchant_center->name : $application->merchant->merchant_name) : $application->name;
                $response['invoice_type'] = $invoice->type;
                if ($invoice->type != 'processing_invoice') {
                    if ($data['state_name'] && $data['state_name'] == $application->merchant->state) {
                        $state_name = ($application->application_element && $application->application_element->center_id > 0 && $application->application_element->merchant_center && $application->application_element->merchant_center->gst_number && $application->application_element->merchant_center->state) ? $application->application_element->merchant_center->state : $application->merchant->state;
                        $response['state'] = isset($_states[$state_name]) ? $_states[$state_name].'-'.$state_name : $state_name;
                    } else if (empty($data['state_name'])) {
                        $state_name = ($application->application_element && $application->application_element->center_id > 0 && $application->application_element->merchant_center && $application->application_element->merchant_center->gst_number && $application->application_element->merchant_center->state) ? $application->application_element->merchant_center->state : $application->merchant->state;
                        $response['state'] = isset($_states[$state_name]) ? $_states[$state_name].'-'.$state_name : $state_name;
                    } else {
                        $append = 0;
                    }
                } else {
                    if ($application->permanent_address_state == "") {
                        if ($data['state_name'] && $data['state_name'] == $application->current_address_state) {
                            $response['state'] = isset($_states[$application->current_address_state]) ? $_states[$application->current_address_state].'-'.$application->current_address_state : $application->current_address_state;
                        } else if (empty($data['state_name'])) {
                            $response['state'] = isset($_states[$application->current_address_state]) ? $_states[$application->current_address_state].'-'.$application->current_address_state : $application->current_address_state;
                        } else {
                            $append = 0;
                        }
                    } else {
                        if ($data['state_name'] && $data['state_name'] == $application->permanent_address_state) {
                            $response['state'] = isset($_states[$application->permanent_address_state]) ? $_states[$application->permanent_address_state].'-'.$application->permanent_address_state : $application->permanent_address_state;
                        } else if (empty($data['state_name'])) {
                            $response['state'] = isset($_states[$application->permanent_address_state]) ? $_states[$application->permanent_address_state].'-'.$application->permanent_address_state : $application->permanent_address_state;
                        } else {
                            $append = 0;
                        }
                    }
                }

                if ($append == 1) {
                    $response['igst'] = 0;
                    $response['sgst'] = 0;
                    $response['cgst'] = 0;

                    if ($process) {
                        foreach ($process as $item) {
                            if ($item['taxes'] == 'IGST') {
                                $response['igst'] = $item['gst_amount'];
                            }
                            if ($item['taxes'] == 'SGST') {
                                $response['sgst'] = $item['gst_amount'];
                            }
                            if ($item['taxes'] == 'CGST') {
                                $response['cgst'] = $item['gst_amount'];
                            }
                        }
                    } else {
                        if (strpos($response['state'], 'Maharashtra') !== false || $response['state'] == "Maharashtra") {
                            $response['cgst'] = round($invoice->cgst, 2);//round(($application->cgst*$application->net_amount)/100,2);
                            $response['sgst'] = round($invoice->sgst, 2);//round(($application->sgst*$application->net_amount)/100,2);
                            $response['igst'] = 0;
                        } else {
                            $response['cgst'] = 0;
                            $response['sgst'] = 0;
                            $response['igst'] = round($invoice->igst, 2);//round(($application->igst*$application->net_amount)/100,2);

                        }
                    }

                    $response['invoice_id'] = $invoice->invoice_id;
                    $disbursedDate = strtotime($this->getDisbursedDate($application->id));
                    $response['invoice_date'] = date('d M Y', $disbursedDate);
                    $response['date'] = $disbursedDate;

                    $full_path = '/admin/consumer-application/get-documents/';

                    $documents = [];
                    foreach ($application->documents as $index => $document) {
                        $type = ($document->file_type == 'Processing Fee Invoice') ? 'processing_invoice' : 'subvention_invoice';

                        $phase = '';
                        $pathsSegments = explode('/',$document->file_path);
                        if (count($pathsSegments) == 3){
                            $phase = $application->id.'/'.$pathsSegments[1].'/merchant_disbursed.pdf';
                        }
                        if (strpos($phase, $document->file_path) !== false && isset($pathsSegments[1])){
                            $type = $type.'_'.$pathsSegments[1];
                        }

                        if (!isset($documents[$type])) {
                            $documents[$type] = $document->file_path;
                        }
                    }

                    $response['subvention_amount'] = 0;

                    if ($invoice->type == 'subvention_invoice') {
                        $response['subvention_amount'] = $response['cgst'] + $response['sgst'] + $response['igst'] + $response['net_amount'];
                    }

                    $type = $invoice->type;

                    if ($invoice->phase_id){
                        $type = $invoice->type.'_'.$invoice->phase_id;
                    }
                    $short_path = isset($documents[$type]) && !empty($documents[$type]) ? $documents[$type] : (isset($documents[$type]) && $application->id . '/' . (($documents[$type]) ? $documents[$type] : (($type == 'processing invoice') ? 'Processing Fee Invoice' : 'merchant_disbursed') . '.pdf'));
                    if ($invoice->type == 'subvention_invoice' && $invoice->phase_id) {
                        $short_path = '/' . $application->id .'/'.$invoice->phase_id. '/merchant_disbursed.pdf';
                    }
                    if (!$short_path) {
                        if ($invoice->type == 'subvention_invoice') {
                            $short_path = '/' . $application->id . '/merchant_disbursed.pdf';
                        } else {
                            $short_path = '/' . $application->id . '/Processing Fee Invoice.pdf';
                        }
                    }
                    $full_path .= $short_path;
                    $full_path = str_replace('//', '/', $full_path);

                    $response['invoice_url'] = $full_path;

                    if ($isZipExport) {


                        $myfile = fopen(storage_path()."/file.txt", "w") or die("Unable to open file!");

                        $content = null;
                        $content1 = null;

                        if ($res === TRUE && $content == null && $content1 == null) {
                            if ($invoice->type == 'processing_invoice') {
                                $_name = $this->getFileUploadedName('Processing Fee Invoice', $application->id);
                                $content = $this->viewFile($application->id, $_name);
                                if ($content) {
                                    $zip->addFile($content, 'Processing_Fee_Invoice_' . $invoice->invoice_id . '.pdf');
                                    $hasData = true;
                                    $txt .= $invoice->invoice_id."\n";
                                    $list[] = $content;
                                }
                            }
                            if ($invoice->type == 'subvention_invoice') {
                                $disburseFileName = 'merchant_disbursed';
                                if ($invoice->phase_id){
                                    $disburseFileName = $invoice->phase_id.'/merchant_disbursed';
                                }
                                $_name = $this->getFileUploadedName($disburseFileName, $application->id, $disburseFileName);
                                $content1 = $this->viewFile($application->id, $_name);
                                if ($content1) {
                                    $zip->addFile($content1, 'Subvention_Fee_Invoice_' . $invoice->invoice_id . '.pdf');
                                    $hasData = true;
                                    $txt .= $invoice->invoice_id."\n";
                                    $list[] = $content1;
                                }
                            }
                        }


                        fwrite($myfile, $txt);
                        fclose($myfile);
                        $content = null;
                        $content1 = null;
                    }

                    $responseData[$application->lender->name][] = $response;
                }
            }
        }


        $responseDataMain = [];
        foreach ($responseData as $lender => $item) {
            usort($item, function ($a, $b) {
                return $a['date'] - $b['date'];
            });

            $responseDataMain[$lender] = $item;
        }

        if ($isZipExport) {
            $zip->close();
            if(!$hasData){
                Session::flash('error', 'No Data Found');
                return redirect()->back();
            }

            foreach($list as $d){
                unlink($d);
            }
            return response()->download($zipFileName)->deleteFileAfterSend(true);
        }


        if ($isFileExport && $responseDataMain){
            $request = new Request(['data' => $this->getCorrectFormat($responseDataMain['K. M. Global Credit Private Limited']), 'sheet' => 'Sheet1']);
            return Excel::download((new Exporter($request)), 'Invoice_'. $from_date . '_to_' . $to_date . '.xls');
        }


        $data['invoices'] = $responseDataMain;
        $data['from_date'] = $from_date;
        $data['to_date'] = $to_date;
        $data['invoice_date'] = $invoice_date;
        $data['merchants'] = Merchant::where('status','active')->where('is_guest_active',1)->get(['id','merchant_name']);
        $data['state'] = StateModel::all();
        return view('admin.showinvoices', $data);
    }

    public function viewSubventionInvoice(Request $request){
        $filing_month = $request->get('month');
        $filing_year = $request->get('year');
        $filing_month = $filing_month + 1;
        $invoice_date = Carbon::createFromDate($filing_year, $filing_month)->endOfMonth()->toDateTimeString();

//        $invoice_date = $request->has('invoice_date') ? Carbon::createFromFormat('Y-m-d', $request->get('invoice_date'))->endOfMonth()->toDateTimeString() : '';
        $merchant_id = $request->has('merchant_id') ? $request->get('merchant_id') : '';

        $query = Invoices::with('merchant','center')->where('invoice_date', $invoice_date)->where('application_id', 0);
        if(!is_null($merchant_id)){
            $query = $query->where('merchant_id', $merchant_id);
        }
        $invoices = $query->get();

        $invoices_list = '<b><center>No Data Found</center></b>';
        if(count($invoices) > 0){
            $invoices_list = '<table class="table"><thead style="background-color: #999999;color: white">
                                    <th>#</th>
                                    <th>Name</th>
                                    <th>State</th>
                                    <th>GSTN</th>
                                    <th>Taxable Amount</th>
                                    <th>CGST</th>
                                    <th>SGST</th>
                                    <th>IGST</th>
                                    <th>Amount</th>
                                    <th>Invoice Id</th>
                                    <th>Invoice Date</th>
                                </thead><tbody>';
            foreach ($invoices as $invoice) {
                $gst = $invoice->merchant->gst_number;
                if(isset($invoice->center) && isset($invoice->center->gst_number)){
                    $gst = $invoice->center->gst_number;
                }
                $state = $invoice->merchant->state;
                if(isset($invoice->center) && isset($invoice->center->state)){
                    $state = $invoice->center->state;
                }
                $invoices_list .= '<tr>
                                    <td>' . ($invoice->merchant_id ?? '') . '</td>
                                    <td>' . ($invoice->merchant->merchant_name ?? ''). '</td>
                                    <td>' . ($state ?? ''). '</td>
                                    <td>' . ($gst ?? ''). '</td>
                                    <td>' . ($invoice->net_amount ?? '') .'</td>
                                    <td>' . ($invoice->cgst ?? '') . '</td>
                                    <td>' . ($invoice->sgst ?? '') . '</td>
                                    <td>' . ($invoice->igst ?? '') . '</td>
                                    <td>' . ($invoice->amount ?? '') .'</td>
                                    <td>' . ($invoice->invoice_id ?? '') . '</td>
                                    <td>' . ($invoice->invoice_date ?? '') . '</td>
                                   </tr>';
            }
            $invoices_list .= '</tbody></table>';
        }
        return response()->json(['status' => 'OK', 'invoice' => $invoices_list]);
    }

    public function exportSubventionInvoice(Request $request){
        $month = $request->get('month');
        $year = $request->get('year');
        $month = $month + 1;
        $invoice_date = Carbon::createFromDate($year, $month)->endOfMonth()->toDateTimeString();
        $date = Carbon::createFromDate($year, $month)->endOfMonth();
        $merchant_id = $request->has('subv_merchant_id') ? $request->get('subv_merchant_id') : '';

        $type = '';
        if(isset($_POST['export_zip'])){
            $type = 'zip';
        }else if($_POST['export_excel']){
            $type = 'excel';
        }

        $user = Auth::user();
        $user_id = $user->id;

        $data = ['invoice_date' => $invoice_date, 'month' => $month, 'year' => $year, 'merchant_id' => $merchant_id, 'type' => $type, 'user_id' => $user_id];

        event(new EventMonthlySubventionInvoice($data));

        /*$jobs = new CampaignsJobProvider();
        $jobs->from = 'export_subvention_invoice';
        $jobs->payload = json_encode($data);
        $jobs->available_at = Carbon::now()->addMinutes(5)->toDateTimeString();
        $jobs->application_id = 181;
        $jobs->created_at = Carbon::now()->toDateTimeString();
        $jobs->is_available = 0;
        $jobs->save();*/

        Session::flash('success', 'You will receive a mail shortly with the data');
        return redirect()->back();
    }

    public function generateBouncePenal(Request $request){
        ini_set('max_execution_time', -1);
        set_time_limit(0);
        ini_set('memory_limit', '-1');

        if (isset($_POST['download_invoices'])) {
            return $this->downloadBouncePenal($request);
        } else if (isset($_POST['generate_invoices'])) {

            $bp_from_date = $request->get('bp_from_date');
            $bp_to_date = $request->get('bp_to_date');

            $isExist = JobProvider::where('from', 'bounce_invoices_creation')->where('payload', 'like', '%{"from_payment_date":"' . $bp_from_date . '","to_payment_date":"' . $bp_to_date . '"%')->first(['id']);
            if (isset($isExist->id)) {
                Session::flash('error', 'Invoices are already generated for the selected date');
                return redirect()->back();
            }

            $payments = PaymentTransaction::where('payment_date', '>=', $bp_from_date)->where('payment_date', '<=', $bp_to_date)->get(['application_id']);
            $applications = [];
            foreach ($payments as $payment) {
                if (!in_array($payment->application_id, $applications)) {
                    $applications[] = $payment->application_id;
                }
            }
            if ($applications) {
                (new LoanManagement())->invoiceCreation($applications, $bp_from_date, $bp_to_date);
                Session::flash('success', 'Invoice creations added in queue');
            } else {
                Session::flash('error', 'No transaction found on the selected date range');
            }

            return redirect()->back();
        }
    }

    public function viewBouncePenal(Request $request){
        $bp_from_date = $request->has('from_date') ? Carbon::createFromFormat('Y-m-d', $request->get('from_date'))->startOfMonth()->toDateTimeString() : '';
        $bp_to_date = $request->has('to_date') ? Carbon::createFromFormat('Y-m-d', $request->get('to_date'))->endOfMonth()->toDateTimeString() : '';

        $charged_invoices = ChargedInvoices::where('invoice_date','>=', $bp_from_date)->where('invoice_date','<=', $bp_to_date)->get();

        if(count($charged_invoices) > 0){
            $charged_invoices_list = '';
            foreach ($charged_invoices as $invoice) {
                $application = ConsumerApplication::where('id', $invoice->application_id)->first(['name','current_address_state','permanent_address_state']);
                $revise_option = empty($invoice->gst_filing_confirmed) && empty($invoice->gst_filing_confirmed_by) ? '<div id="revise_btn" class="btn btn-sm btn-primary" data-id="'.$invoice->id.'" data-app-id="'.$invoice->application_id.'" data-type="'.$invoice->type.'" >Revise invoice</div>' : '';
                $charged_invoices_list .= '<tr>
                                                <td>' . ($invoice->application_id ?? '') . '</td>
                                                <td>' . ($application->name ?? ''). '</td>
                                                <td>' . (isset($application->permanent_address_state) && !empty($application->permanent_address_state) ? $application->permanent_address_state : (isset($application->current_address_state) && !empty($application->current_address_state) ? $application->current_address_state : '')) . '</td>
                                                <td>' . ($invoice->amount - ($invoice->igst + $invoice->cgst + $invoice->sgst)) . '</td>
                                                <td>' . ($invoice->cgst ?? '') . '</td>
                                                <td>' . ($invoice->sgst ?? '') . '</td>
                                                <td>' . ($invoice->igst ?? '') . '</td>
                                                <td>' . ($invoice->amount ?? '') . '</td>
                                                <td>' . ($invoice->invoice_id ?? '') . '</td>
                                                <td>' . ($invoice->invoice_date ?? '') . '</td>
                                                <td>' . ($invoice->type ?? '') . '</td>
                                                <td>' . $revise_option . '</td>
                                            </tr>';
            }

            return response()->json(['status' => 'OK', 'invoice' => $charged_invoices_list]);
        }
        return 'false';
    }

    public function downloadBouncePenal($request){
        $bp_from_date = $request->has('bp_from_date') ? Carbon::createFromFormat('Y-m-d', $request->get('bp_from_date'))->startOfMonth()->toDateTimeString() : '';
        $bp_to_date = $request->has('bp_to_date') ? Carbon::createFromFormat('Y-m-d', $request->get('bp_to_date'))->endOfMonth()->toDateTimeString() : '';

        $chargedInvoices = ChargedInvoices::where('invoice_date','>=', $bp_from_date)->where('invoice_date','<=', $bp_to_date)->get();

        $hasData = false;
        $this->isInternal = true;
        $zip = new \ZipArchive();
        $zipFileName = 'invoice_' . Carbon::now()->toDateTimeString() . '.zip';
        $res = $zip->open(storage_path($zipFileName), \ZipArchive::CREATE);
        $list = [];

        foreach ($chargedInvoices as $invoice) {
            $application = ConsumerApplication::where('id', $invoice->application_id)->first();

            $myfile = fopen(storage_path()."/file.txt", "w") or die("Unable to open file!");

            $content = null;
            $content1 = null;
            $txt = '';

            $file_type = $invoice->type.'_'.strtolower(str_replace('-',' ',$invoice->invoice_id));
            if ($res === TRUE && $content == null && $content1 == null) {
                if ($invoice->type == 'bounce') {
                    $_name = $this->getFileUploadedName($file_type, $application->id);
                    $content = $this->viewFile($application->id, $_name);
                    if(!$content){
                        $file_type = $invoice->type.'_'.$invoice->invoice_id;
                        $_name = $this->getFileUploadedName($file_type, $application->id);
                        $content = $this->viewFile($application->id, $_name);
                    }
                    if ($content) {
                        $zip->addFile($content, 'Bounce_charge_Invoice_' . $invoice->invoice_id . '.pdf');
                        $hasData = true;
                        $txt .= $invoice->invoice_id."\n";
                        $list[] = $content;
                    }
                }
                if ($invoice->type == 'penal') {
                    $_name = $this->getFileUploadedName($file_type, $application->id);
                    $content1 = $this->viewFile($application->id, $_name);
                    if(!$content1){
                        $file_type = $invoice->type.'_'.$invoice->invoice_id;
                        $_name = $this->getFileUploadedName($file_type, $application->id);
                        $content1 = $this->viewFile($application->id, $_name);
                    }
                    if ($content1) {
                        $zip->addFile($content1, 'Penal_charge_Invoice_' . $invoice->invoice_id . '.pdf');
                        $hasData = true;
                        $txt .= $invoice->invoice_id."\n";
                        $list[] = $content1;
                    }
                }
            }


            fwrite($myfile, $txt);
            fclose($myfile);
            $content = null;
            $content1 = null;
        }

        $zip->close();
        if(!$hasData){
            Session::flash('error', 'No Data Found');
            return redirect()->back();
        }

        foreach($list as $d){
            unlink($d);
        }

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


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

        $revised = (new LoanManagement())->reviseBouncePenal($id, $application_id, $type, $user_id);

        if($revised){
            Session::flash('success', 'Invoice revised Successfully');
        }else{
            Session::flash('error', 'Error in revision');
        }


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

    public function getFileUploadedName($name, $application_id, $path = false){
        $_file_path = '';
        if($path){
            $_file_path = ConsumerApplicationFiles::where('consumer_application_id', $application_id)->where('file_path', 'like','%'.$path.'%')->orderBy('created_at','desc')->first(['file_path']);
        }else{
            $_file_path = ConsumerApplicationFiles::where('consumer_application_id', $application_id)->where('file_type', $name)->orderBy('created_at','desc')->first(['file_path']);
        }

        if(isset($_file_path->file_path)){  
            $_file_path = explode('/',$_file_path->file_path);
            if (is_array($_file_path)){
                $name = $_file_path[count($_file_path) - 1];
            }
        }
        return $name;
    }

    public function maskOSVProof($id, Request  $request){
        $file = ConsumerApplicationFiles::where('id', $request->get('file_id'))->first();
        $app = ConsumerApplication::where('id', $id)->first(['lender_id']);
        $pathSeg = explode('/', $file->file_path);
        $pathExp = $pathSeg[count($pathSeg) - 1];
        $pathExtA = explode('.', $pathExp);
        $pathExt = '.pdf';
        if(isset($pathExtA[1])){
            $pathExt = '.'.$pathExtA[1];
        }

        $imagePdf = new ImagePDFSignature();
        $document = new ConsumerDocument($request);
        if($pathExt == '.pdf'){
            $imageOut = $imagePdf->signPDF($file->file_type, $file->file_path, $app);
        }else{
            $imageOut = $imagePdf->signImage($pathExt, $file->file_type, $file->file_path, $app);
        }
        $document->uploadToS3($file->file_type.'_masked', $id, $imageOut['file'], '.pdf', true);
        if(file_exists(public_path($imageOut['path']))){
            unlink(public_path($imageOut['path']));
        }
        return response()->json(['status' => 'OK', 'message' => 'File generated']);
    }

    public function showFileToMerchant($application_id, Request $request){

        try{
            $isMultiPhase = false;
            $total_disbursed_phases = 0;

            $file = ConsumerApplicationFiles::where('id', $request->get('file_id'))->first();
            $application = ConsumerApplication::where('id', $application_id)->first(['offer_id']);

            $offer_id = $application->offer_id;
            $disbursementOffers = DisbursementOffers::where('application_id', $application_id)->where('offer_id', $offer_id)->orderBy('phase','asc')->get();
            $total_phases = count($disbursementOffers);

            $files_already_shown = ConsumerApplicationFiles::where('consumer_application_id',$application_id)->where('show_to_merchant', 1)->where('file_type',$file->file_type)->whereNull('deleted_at')->get();
            $total_files_shown = count($files_already_shown);
            if ($total_phases > 0) {
                $isMultiPhase = true;
                $offer_ids = [];
                foreach ($disbursementOffers as $offer) {
                    $offer_ids[] = $offer->id;
                }
                $disbursementLogs = DisbursementLogs::where('application_id', $application_id)->whereIn('disbursement_offer_id', $offer_ids)->orderBy('phase','asc')->get();
                $total_disbursed_phases = count($disbursementLogs);
            }

            if($total_files_shown > 0) {
                // if (($total_files_shown >= $total_disbursed_phases && $isMultiPhase) || ($total_files_shown > 0 && !$isMultiPhase)){
                return response()->json(['status' => 'FAIL', 'message' => 'Already an unsigned DA exists']);
                // }
            }

            ConsumerApplicationFiles::where('consumer_application_id', $application_id)->where('id', $request->get('file_id'))->where('file_type',$file->file_type)->update(['show_to_merchant' => 1]);

        }catch (\Exception $e){
            (new Slack(new Request(['title' => 'Show File To Merchant Request Error', 'fields' => ['e' => $e->getMessage(),'l' => $e->getLine(),'t' => $e->getTraceAsString(), 'id' => $application_id], 'group' => Slack::$STAGE_TESTING])))->send();
            \Session::flash('error', 'Something went wrong');
            return response()->json(['status' => 'FAIL', 'message' => 'Something went wrong']);
        }
        return response()->json(['status' => 'OK', 'message' => 'File Sent']);
    }

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

        try{
            $file = ConsumerApplicationFiles::where('id', $request->get('file_id'))->first();
            if (isset($file->id)) {
                $application_id = $file->consumer_application_id;
                ConsumerApplicationFiles::where('consumer_application_id', $application_id)->where('show_to_merchant', 1)->where('file_type',$file->file_type)->update(['show_to_merchant' => 0]);
            }

        }catch (\Exception $e){
            (new Slack(new Request(['title' => 'Cancel File To Merchant Request Error', 'fields' => ['e' => $e->getMessage(),'l' => $e->getLine(),'t' => $e->getTraceAsString(), 'id' => $id], 'group' => Slack::$STAGE_TESTING])))->send();
            \Session::flash('error', 'Something went wrong');
            return redirect()->back();
        }
        return response()->json(['status' => 'OK', 'message' => 'File Cancelled']);
    }

    public function getCorrectFormat($data){
        $response[] = ['Application Id','Lender ID', 'Invoice ID', 'Name', 'Name on Invoice', 'State', 'GST Number','Subvention Amount','Processing Fee', 'Invoice Value', 'Taxable Value', 'IGST','CGST','SGST','Invoice Date','Status', 'Type'];
        foreach ($data as $item){
            $response[] = [
                'application_id' => $item['application_id'],
                'lender_id' => $item['lender_id'],
                'invoice_id' => $item['invoice_id'],
                'name' => $item['name'],
                'name_on_invoice' => $item['name_on_invoice'],
                'state' => $item['state'],
                'gst_number' => $item['gst_number'],
                'subvention_amount' => $item['subvention_amount'],
                'processing_fee' => $item['amount'],
                'invoice_value' => $item['subvention_amount'] > 0 ? $item['subvention_amount'] : $item['amount'],
                'taxable_value' => $item['net_amount'],
                'igst' => $item['igst'],
                'cgst' => $item['cgst'],
                'sgst' => $item['sgst'],
                'invoice_date' =>  date('Y-m-d',strtotime($item['invoice_date'])),
                'status' => $item['status'],
                'type' => $item['invoice_type']
            ];
        }

        return $response;
    }

    function getDisbursedDate($id)
    {
        $status = StatusLogs::where('application_id', $id)
            ->where('status', 'disbursed')
            ->orderBy('id', 'desc')->first(['created_at']);

        return isset($status->created_at) ? $status->created_at : '';
    }

    public function zipIt(\ZipArchive $zip, $application)
    {
        $content = $this->viewFile($application->id, 'Processing Fee Invoice.pdf');
        $zip->addFile($content, 'Processing Fee Invoice ' . $application->name . '.pdf');
        return $zip;
    }

    public function cancelraazorpaylink($data)
    {
        try {
            if ($data['lender_id'] == 2) {
                $api = new Api(_env('KMRAZORPAYKEY', ''), _env('KMRAZORPAYSECRET', ''));
            } else {
                $api = new Api(_env('PRIDERAZORPAYKEY', ''), _env('PRIDERAZORPAYSECRET', ''));
            }
            $paymnet_id = $data['payment_id'];
            $link = $api->invoice->fetch($paymnet_id);
            DB::statement("update online_payments set status = 'cancelled' where payment_id = '" . $paymnet_id . "'");
            $link->cancel();
        } catch (\Exception $e) {
            $f = $e;
        }
    }

    public function callRazorPaySettlementAPI($data){
        if ($data['lender_id'] == 2) {
            $api = new Api(_env('KMRAZORPAYKEY', ''), _env('KMRAZORPAYSECRET', ''));
        } else {
            $api = new Api(_env('PRIDERAZORPAYKEY', ''), _env('PRIDERAZORPAYSECRET', ''));
        }

        $settlement_date = isset($data['settlement_date']) ? $data['settlement_date'] : Carbon::now()->toDateString();
        $from = strtotime($settlement_date);
        $to = Carbon::parse($settlement_date)->addDay(3)->timestamp;

        $settlementObject = $api->settlement->all(['from' => $from, 'to' => $to]);

        $settlementData = [];
        if(isset($settlementObject['count'])) {
            foreach ($settlementObject['items'] as $settlementItem) {
                $date = date('Y-m-d', $settlementItem->created_at);
                if($settlementItem->status == 'processed' && strtotime($date) >= $from && strtotime($date) <= $to) {
                    $settlement = $this->getSettlementReportWithCustomer($settlementItem, $data);
                    if ($settlement != 'error') {
                        $settlementData[$settlementItem->id] = ['date' => $date, 'settlement' => $settlement, 'data' => $settlementItem];
                    } else {
                        (new Slack(new Request(['title' => __FUNCTION__ . ' Error', 'fields' => ['error' => json_encode($settlement)]])))->send();
                        break;
                    }
                }
            }
        }else{
            return 'error';
        }
        return $settlementData;
    }

    public function callPayTMSettlementAPI($data){
        if ($data['lender_id'] == 2) {
            $api = new PayTMSettlement(_env('PAYTM_SETTLEMENT_KEY_KM'));
        } else {
            $api = new PayTMSettlement(_env('PAYTM_SETTLEMENT_KEY_KM'));
        }

        $settlement_date = isset($data['settlement_date']) ? $data['settlement_date'] : Carbon::now()->toDateString();
        $from = strtotime($settlement_date);
        $to = Carbon::parse($settlement_date)->addDay(3)->timestamp;

        (new Slack(new Request(['title' => 'Tally Settlement (Before Settlement)', 'fields' => ['Settlement Date' => $settlement_date], 'group' => Slack::$TALLY_INTEGRATION])))->send();
        $settlementObject = $api->getSettlement($settlement_date);
        $settlementObject = $this->getBulkSettlementEntries($settlementObject, $settlement_date, $api);
        (new Slack(new Request(['title' => 'Tally Settlement (After Settlement Entries)', 'fields' => ['Settlement Date' => $settlement_date, 'res' => json_encode($settlementObject)], 'group' => Slack::$TALLY_INTEGRATION])))->send();
        $settlementData = [];
        if(isset($settlementObject['status']) && $settlementObject['status'] == 'SUCCESS' && isset($settlementObject['settlementListResponse']['totalCount'])) {
            foreach ($settlementObject['settlementListResponse']['settlementTransactionList'] as $settlementItem) {
                $date = date('Y-m-d', strtotime($settlementItem['SETTLED DATE']));
                if(strtotime($date) >= $from && strtotime($date) <= $to) {
                    if ($settlementItem['TXNID']) {
                        $settlementData[$settlementItem['TXNID']] = ['date' => $date, 'data' => $settlementItem];
                    } else {
                        (new Slack(new Request(['title' => __FUNCTION__ . ' Error', 'fields' => ['error' => json_encode($settlementObject)]])))->send();
                        break;
                    }
                }
            }
        }else{
            return 'error';
        }
        return $settlementData;
    }

    public function getBulkSettlementEntries($res, $settlement_date, $api, $pageNum = 2){
        $settlementData = [];
        (new Slack(new Request(['title' => 'Tally Settlement (Before Settlement Entries)',
            'fields' => ['Settlement Date' => $settlement_date, 'res' => json_encode($res), 'api' => $api, 'count' => $res['settlementListResponse']['totalCount']], 'group' => Slack::$TALLY_INTEGRATION])))->send();
        try {
            if (isset($res['settlementListResponse']['settlementTransactionList'])) {
                $settlementData = array_merge($settlementData, $res['settlementListResponse']['settlementTransactionList']);
                for ($i = $pageNum; $i <= $res['settlementListResponse']['paginatorTotalPage']; $i++) {
                    $settlementDataItem = $api->getSettlement($settlement_date, $i);
                    $settlementData = array_merge($settlementData, $settlementDataItem['settlementListResponse']['settlementTransactionList']);
                }
            }

            $res['settlementListResponse']['settlementTransactionList'] = $settlementData;

            return $res;
        }catch (\Exception $e) {
            (new Slack(new Request(['title'=>'Tally Settlement (Exception)','fields'=>['error'=>$e->getMessage(),'line'=>$e->getLine(),'trace'=>$e->getTraceAsString()], 'group' => Slack::$TALLY_INTEGRATION])))->send();
        }
    }

    public function getSettlementReportWithCustomer($payment, $data){

        if ($data['lender_id'] == 2) {
            $api = new Api(_env('KMRAZORPAYKEY', ''), _env('KMRAZORPAYSECRET', ''));
        } else {
            $api = new Api(_env('PRIDERAZORPAYKEY', ''), _env('PRIDERAZORPAYSECRET', ''));
        }



        $yyyy = date('Y', $payment->created_at);
        $mm = date('m', $payment->created_at);

        $payments = $api->settlement->reports(['year' => $yyyy,'month' => $mm]);


        $paymentData = [];
        $paymentIds = [];
        $p_amount = 0;
        $s_amount = 0;
        foreach ($payments as $paymentItem){
            if($paymentItem->type == 'payment') {
                $paymentFetch = $api->payment->fetch($paymentItem->entity_id);
                $paymentData[$paymentFetch->invoice_id] = $paymentFetch;
                $paymentIds[] = $paymentFetch->invoice_id;
                $p_amount += $paymentItem->amount;
            }else{
                $s_amount += $paymentItem->amount;
            }

        }

        $mandateDataDatabase = OnlinePayment::with('application')->whereIn('payment_id', $paymentIds)->get();
        $mandateDataDatabaseConsumer = [];
        foreach ($mandateDataDatabase as $item){
            $mandateDataDatabaseConsumer[$item->payment_id] = $item->application;
        }
        $receivedData = [];
        foreach ($paymentData as $payment_id => $paymentDataItem){
            $receivedData[] = ['settlement' => $paymentDataItem, 'application' => isset($mandateDataDatabaseConsumer[$payment_id]) ? $mandateDataDatabaseConsumer[$payment_id] : 0];
        }

        return $receivedData;
    }

    private function initAvProcess($id){
        $application = ConsumerApplication::where('id', $id)->first(['id','name','mobile_number','email']);
        $avlid = AvanseCreateFinance::getAvanseLoanId($application->id);
        if (false !== $avlid) {
            $razorpaydata['laNumber'] = $avlid;
            $razorpaydata['id'] = $application->id;
            $rece = [];
            $recv[0]['name'] = !empty($application->name) ? $application->name : '';
            $recv[0]['mobileNumber'] = !empty($application->mobile_number) ? $application->mobile_number : '';
            $recv[0]['emailId'] = !empty($application->email) ? $application->email : '';
            $recv[0]['accountName'] = "Applicant";
            $razorpaydata['receipents'] = $recv;
            return AvanseProcesses::getPaymentLink($razorpaydata);
        }
        return '';
    }

    public function getrazorpaylink($data = null)
    {
        //Request $request
        //$data

        // $data = $request->all();

        $data = $data ?? request()->all();



        if($data['purpose'] == 'settlement_payment'){
            $data['custom_date'] = Carbon::now()->addDays(2)->toDateString();
        }

        if($data['lender_id'] == 2){
            $payment_gateway = 'PAYTM';
//            $payment_gateway = 'RazorPay';
//        }elseif($data['lender_id'] == AvanseServices::$lender_id){
//            $payment_gateway = 'RazorPay';
        }else if($data['lender_id'] == Services::$lender_id){
            $payment_gateway = 'RazorPay';//'RazorPay';
        }else if($data['lender_id'] == LendBox::$lender_id || $data['lender_id'] == LendBoxLSP::$lender_id){
            $payment_gateway = 'RazorPay';
        }else if($data['lender_id'] == AvanseServices::$lender_id){
            $payment_gateway = 'RazorPay';
        }else if($data['lender_id'] == KMGP2P::$lender_id){
            $payment_gateway = 'RazorPay';
        }else if($data['lender_id'] == JMServices::$lender_id){
            $payment_gateway = 'RazorPay';
        }else if($data['lender_id'] == Vivriti::$lender_id) {
            $payment_gateway = 'RazorPay';
        }else if($data['lender_id'] == BlackSoil::$lender_id) {
            $payment_gateway = 'RazorPay';
        }else{
            $payment_gateway = 'PAYTM';
           // $payment_gateway = 'RazorPay';
        }
        $amount = 0;
        $application_id = $data['id'];
        if($payment_gateway == 'RazorPay') {
            if ($data['lender_id'] == 2) {
                $api = new Api(_env('KMRAZORPAYKEY', ''), _env('KMRAZORPAYSECRET', ''));
            }elseif($data['lender_id'] == AvanseServices::$lender_id){
                //return $this->initAvProcess($data['id']);
                $api = new Api(_env('AVANSERAZORPAYKEY', ''), _env('AVANSERAZORPAYSECRET', ''));
            }elseif($data['lender_id'] == Services::$lender_id){
                $api = new Api(_env('ABFLRAZORPAYKEY', ''), _env('ABFLRAZORPAYSECRET', ''));
            }elseif($data['lender_id'] == LendBox::$lender_id || $data['lender_id'] == LendBoxLSP::$lender_id){
                $api = new Api(_env('LENDBOX_RAZORPAYKEY', ''), _env('LENDBOX_RAZORPAYSECRET', ''));
            }elseif($data['lender_id'] == KMGP2P::$lender_id){
                $api = new Api(_env('KMGP2PRAZORPAYKEY', ''), _env('KMGP2PRAZORPAYSECRET', ''));
            }elseif($data['lender_id'] == JMServices::$lender_id){
                $api = new Api(_env('JMFLRAZORPAYKEY', ''), _env('JMFLRAZORPAYSECRET', ''));
            }elseif($data['lender_id'] == Vivriti::$lender_id){
                $api = new Api(_env('VIVRITIRAZORPAYKEY', ''), _env('VIVRITIRAZORPAYSECRET', ''));
            }elseif($data['lender_id'] == BlackSoil::$lender_id){
                $api = new Api(_env('BLACKSOILRAZORPAYKEY', ''), _env('BLACKSOILRAZORPAYSECRET', ''));
            } else {
                $api = new Api(_env('PRIDERAZORPAYKEY', ''), _env('PRIDERAZORPAYSECRET', ''));
            }
            $url = "";
            $amount = round($data['amount'], 2) * 100;

            $descrption = 'For Creditfair EMI';
            $email = $data['email'];

            if($data['purpose'] == 'processing_fee' || $data['purpose'] == 'insurance_fee' || $data['purpose'] == 'advance_amount' || $data['purpose'] == 'total_fee'){
                if(_env('MODETYPE') == "link"){
                    $link = $api->invoice->create(array('type' => 'link', 'amount' => $amount, 'description' => $descrption, 'customer' => array('email' => ""), 'notes' => ['application_id' => $application_id]));
                    //return '';
                    //$link = $api->paymentLink->create(array('amount'=>$amount, 'currency'=>'INR', 'description' => $descrption, 'customer' => array('email' => ""),'notes'=>['application_id' => $application_id],'callback_url' => url('/').'/razorpay_payment_response','callback_method'=>'get'));
                }else{
                    $link = $api->invoice->create(array('type' => 'link', 'amount' => $amount, 'description' => $descrption, 'customer' => array('email' => ""), 'notes' => ['application_id' => $application_id]));
                }
            }else {
                $expire_by = Carbon::createFromFormat('Y-m-d', isset($data['custom_date']) ? $data['custom_date'] : $data['emi_date'])->endOfDay()->timestamp;
                if ($data['purpose'] == 'emi') {
                    $expire_by = Carbon::createFromFormat('Y-m-d', isset($data['custom_date']) ? $data['custom_date'] : $data['emi_date'])->addDay(1)->endOfDay()->timestamp;
                }
                $link = $api->invoice->create(array('type' => 'link', 'amount' => $amount, 'description' => $descrption, 'expire_by' => $expire_by, 'customer' => array('email' => ""), 'notes' => ['application_id' => $application_id]));
            }
            if (isset($link->short_url)) {
                $url = $link->short_url;
            }
            $payment_id = $link->id;
            $amount = $amount /100;
        }else{

            if ($data['lender_id'] == AvanseServices::$lender_id && $data['purpose'] != 'processing_fee') {
                //$url = "";
                //return $url;
            }
            $hashids = new Hashids('Creditfair by CS', 20);
            $hashed_id = $hashids->encode($application_id);

            if(isset($data['customer_amount_link']) && $data['customer_amount_link'] == false){
                $url = asset("paytm/" . $hashed_id);
            }else {
                $amount_string = $data['amount'];
                $amount = $data['amount'];
                if (isset($data['is_foreclosure']) && $data['is_foreclosure'] == 1) {
                    $amount_string = $data['amount'] . '|' . $data['foreclosure_date'];
                } elseif ($data['purpose'] == 'processing_fee') {
                    $amount_string = $data['amount'] . '|' . '0' . '|processing_fee';
                } elseif ($data['purpose'] == 'insurance_fee') {
                    $amount_string = $data['amount'] . '|' . '0' . '|insurance_fee';
                } elseif ($data['purpose'] == 'advance_amount') {
                    $amount_string = $data['amount'] . '|' . '0' . '|advance_amount';
                } elseif ($data['purpose'] == 'emi_and_processing_fee') {
                    $amount_string = $data['amount'] . '|' . '0' . '|emi_and_processing_fee';
                } elseif ($data['purpose'] == 'legal_charges') {
                    $amount_string = $data['amount'] . '|' . '0' . '|legal_charges';
                } elseif ($data['purpose'] == 'total_fee') {
                    $amount_string = $data['amount'] . '|' . '0' . '|total_fee';
                } elseif ($data['purpose'] == 'settlement_payment') {
                    $amount_string = $data['amount'] . '|' . '0' . '|settlement_payment';
                } elseif ($data['purpose'] == 'pre_part_payment') {
                    $amount_string = $data['amount'] . '|' . '0' . '|pre_part_payment|'.(isset($data['pre_part_payment_type']) ? $data['pre_part_payment_type'] : 0);
                }
                $amount_hash = base64_encode(wall_encrypt($amount_string));
                
                $url = asset("paytm/" . $hashed_id . "?data=" . $amount_hash);
            }
            try{
                $url = Shortio::getUrl($url);
                //(new Slack(new Request(['title'=>'Message (Short Testing)','fields'=>['url' => $url]])))->send();
            }catch (\Exception $e) {
                //(new Slack(new Request(['title'=>'Message Errsor (Short Testing)','fields'=>['Application ID'=>$application_id,'error'=>$e->getMessage(),'line'=>$e->getLine(),'trace'=>$e->getTraceAsString()]])))->send();
            }
        }

        $payment = new OnlinePayment();
        $linkExists = $payment::where(['application_id' => $application_id, 'payment_link' => $url, 'purpose' => $data['purpose'], 'amount' => $amount])->get(['id']);
        if ($linkExists->count() == 0) {
            $payment->application_id = $application_id;
            $payment->payment_id = isset($payment_id) ? $payment_id : '';
            $payment->payment_link = $url;
            $payment->purpose = $data['purpose'];
            $payment->emi_date = isset($data['emi_date']) ? $data['emi_date'] : '';
            $payment->amount = $amount;
            $payment->status = isset($link) ? $link->status : 'pending';
            $payment->foreclosure_date = isset($data['foreclosure_date']) ? $data['foreclosure_date'] : 0;
            $payment->pre_part_payment_type = isset($data['pre_part_payment_type']) ? $data['pre_part_payment_type'] : 0;

            $payment->save();
        }
        return $url;
    }

    public function fetchAvanseUTR(){

        $jobs = JobProvider::where('from','initiateUTRStatusAvanse')->where('is_available', 0)->get(['id']);

        if(!count($jobs)){
            return response()->json(['status' => 'FAIL', 'message' => 'No UTR Pending'], 200);
        }

        $jobIds = [];
        foreach($jobs as $job){
            $jobIds[] = $job->id;
        }

        if($jobIds) {
            JobProvider::whereIn('id', $jobIds)->update(['available_at' => Carbon::now()->toDateTimeString()]);
            return response()->json(['status' => 'OK', 'message' => 'Avanse UTR Fetch Initiated. You will get the update on slack'], 200);
        }else{
            return response()->json(['status' => 'FAIL', 'message' => 'Failed To Initiate Avanse UTR'], 200);
        }
    }

    public function getDPD($application_id, $applicant_type = 1, $type = '')
    {
        try {
            //$file = Storage::disk('www')->get("1142_response.json");
            $soft_applicant_type = $applicant_type;
            $applicant_type = (empty($applicant_type) || $applicant_type == 1) ? '' : '_'.$applicant_type;
            $type = $type.$applicant_type;
            $file_path = $application_id.'/'.$application_id . '_response' . $type . '.json';
            $soft_file_path = $application_id.'/'.$application_id . '_response_experian_soft_' . $soft_applicant_type . '.json';
            // $myfile = fopen($file_path, "r") or die("Unable to open file!");
            // $file = fread($myfile, filesize($file_path));
            if (false === $report = Equifax::readFile($file_path)) {
                if (false === $report = Equifax::readFile($soft_file_path)) {
                    return false;
                }
            }
        } catch (\Exception $e) {
            return false;
        }
        // -------------------  Uncomment below block for local file reading -----------------
        // try {
        //     // Define file paths
        //     $applicant_type_suffix = (empty($applicant_type) || $applicant_type == 1) ? '' : '_'.$applicant_type;
        //     $type_suffix = $type.$applicant_type_suffix;
        //     $file_path = 'experian_response.json';
        //     $soft_file_path = 'response_soft.json';

        //     // Define the storage path
        //     $storage_path = 'public'; // Use 'public' disk if files are under storage/app/public

        //     // Try to read the primary file
        //     if (Storage::disk($storage_path)->exists($file_path)) {
        //         $report = Storage::disk($storage_path)->get($file_path);
        //     }
        //     // Try to read the secondary (soft) file
        //     elseif (Storage::disk($storage_path)->exists($soft_file_path)) {
        //         $report = Storage::disk($storage_path)->get($soft_file_path);
        //     } else {
        //         return false;
        //     }

        //     // return $report;
        // } catch (\Exception $e) {
        //     // Log exception if needed
        //     \Log::error('Error reading file: '.$e->getMessage());
        //     return false;
        // }

        // Initialize an associative array for the statuses you want to track
        $status_counts = [
            'Sub' => 0,
            'DBT' => 0,
            'Loss' => 0,
            'Settled' => 0,
            'Post (WO) Settled' => 0,
            'Written-off' => 0,
            'Suit Filed' => 0,
            'Wilful default' => 0,
        ];

        //$payment_status = ['000','NEW','CLSD','0','*','STD'];
        $payment_status = ['01+','1+', '30+', '60+', '90+', '120+', '180+', '360+', '540+', '720+', 'SPM', 'SUB', 'DBT'];
        $response = array();
        $current_date = date('Y-m-') . "01";
        $three_month = date("Y-m-", strtotime("-3 months")) . "01";
        $six_month = date("Y-m-", strtotime("-6 months")) . "01";
        $twelve_month = date("Y-m-", strtotime("-12 months")) . "01";
        $three_years_ago = date('Ymd', strtotime('-36 months'));

        $payment_status_weights = [
            '01+' => 2,
            '1+' => 2,
            '30+' => 31,
            '60+' => 61,
            '90+' => 91,
            '120+' => 121,
            '180+' => 181,
            '360+' => 361,
            '540+' => 541,
            '720+' => 721
        ];

        // Default weight for payment statuses that do not exist in the weights array
        $default_weight = 0;

        $max_dpd_days_3m = 0;
        $max_0_plus_dpd_3m = 0;
        $max_0_plus_dpd_3m_count = 0;
        $max_dpd_days_6m = 0;
        $max_30_plus_dpd_6m = 30;
        $max_30_plus_dpd_6m_count = 0;
        $max_dpd_days_12m = 0;
        $max_90_plus_dpd_12m = 90;
        $max_90_plus_dpd_12m_count = 0;
        $totalActiveRestructuredLoans = 0;

        $file = json_decode($report, TRUE);
        if (isset($file['soapenv:Envelope']['soapenv:Body'])) {
            if (isset($file['soapenv:Envelope']['soapenv:Body']['sch:InquiryResponse']['sch:ReportData']['sch:AccountDetails']['sch:Account'])) {
                $data = $file['soapenv:Envelope']['soapenv:Body']['sch:InquiryResponse']['sch:ReportData']['sch:AccountDetails']['sch:Account'];

                if (!isset($data[0])) {
                    $accountsSummary[] = $data;
                } else {
                    $accountsSummary = $data;
                }

                foreach ($accountsSummary as $accounts) {
                    if (isset($accounts['sch:History48Months']) && is_array($accounts['sch:History48Months'])) {
                        foreach ($accounts['sch:History48Months'] as $key => $account) {
                            foreach ($account as $accounthistory) {

                                if (isset($accounts['sch:SanctionAmount']) && $accounts['sch:SanctionAmount'] != 0 && $accounts['sch:SanctionAmount'] != "") {
                                    $approvedamount = $accounts['sch:SanctionAmount'];
                                } elseif (isset($accounts['sch:CreditLimit']) && $accounts['sch:CreditLimit'] != 0 && $accounts['sch:CreditLimit'] != "") {
                                    $approvedamount = $accounts['sch:CreditLimit'];
                                } else {
                                    $approvedamount = 0;
                                }

                                $dateOpened = isset($accounts['sch:DateOpened']) ? $accounts['sch:DateOpened'] : '';
                                $response[$accounts['sch:AccountType']][$dateOpened][$approvedamount]['AccountStatus'] = isset($accounts['sch:AccountStatus']) ? $accounts['sch:AccountStatus'] : '';

                                if (isset($accounthistory['@key']) && isset($accounthistory['sch:PaymentStatus']) && in_array($accounthistory['sch:PaymentStatus'], $payment_status)) {
                                    $date_array = explode('-', $accounthistory['@key']);
                                    $accounthistory['@key'] = date('Y-m-d', strtotime($date_array[1] . '-' . $date_array[0] . "-01"));
                                    $AccountType = (isset($accounts['sch:AccountType'])) ? $accounts['sch:AccountType'] : "";
                                    $DateOpened = (isset($accounts['sch:DateOpened'])) ? $accounts['sch:DateOpened'] : "";

                                    // Get the weight (number of days) of the current DPD status
                                    // $current_dpd_days = $payment_status_weights[$accounthistory['sch:PaymentStatus']];

                                    $paymentStatus = $accounthistory['sch:PaymentStatus'];
                                    $current_dpd_days = isset($payment_status_weights[$paymentStatus]) ? $payment_status_weights[$paymentStatus] : $default_weight;

                                    // 3 month DPD
                                    if ($this->check_in_range($three_month, $current_date, $accounthistory['@key'])) {
                                        $max_dpd_days_3m = max($max_dpd_days_3m, $current_dpd_days);
                                        $max_dpd_days_3m = max($max_dpd_days_3m, $current_dpd_days);
                                    }

                                    // 6 month DPD
                                    if ($this->check_in_range($six_month, $current_date, $accounthistory['@key'])) {
                                        if (isset($response[$AccountType][$DateOpened][$approvedamount]['six']['dpd'])) {
                                            $response[$AccountType][$DateOpened][$approvedamount]['six']['dpd'] = $response[$AccountType][$DateOpened][$approvedamount]['six']['dpd'] + 1;
                                        } else {
                                            $response[$AccountType][$DateOpened][$approvedamount]['six']['dpd'] = 1;
                                        }
                                        $max_dpd_days_6m = max($max_dpd_days_6m, $current_dpd_days);
                                    }

                                    // 12 month DPD
                                    if ($this->check_in_range($twelve_month, $current_date, $accounthistory['@key'])) {
                                        $max_dpd_days_12m = max($max_dpd_days_12m, $current_dpd_days);
                                        if (isset($response[$AccountType][$DateOpened][$approvedamount]['twelve']['dpd'])) {
                                            $response[$AccountType][$DateOpened][$approvedamount]['twelve']['dpd'] = $response[$AccountType][$DateOpened][$approvedamount]['twelve']['dpd'] + 1;
                                        } else {
                                            $response[$AccountType][$DateOpened][$approvedamount]['twelve']['dpd'] = 1;
                                    }
                                }
                            }
                        }
                    }
                }
                $date_opened_ = isset($accounts['sch:DateOpened']) ? str_replace('-', '', $accounts['sch:DateOpened']) : '';

                $accountStatus = isset($accounts['sch:AccountStatus']) ? $accounts['sch:AccountStatus'] : null;
                $dateClosed = isset($accounts['sch:DateClosed']) ? $accounts['sch:DateClosed'] : null;

                // Check if the account is active (Date_Closed is null)
                if (is_null($dateClosed) && isset($accountStatus)) {

                    // Check if the status name includes "Restructured" and exclude "Restructured due to COVID-19"
                    if ($accountStatus && strpos($accountStatus, 'Restructured') !== false && $accountStatus !== 'Restructured due to COVID-19') {
                        $totalActiveRestructuredLoans++;
                    }
                }

                // Compare the Open_Date with the date from 36 months ago
                if (isset($date_opened) && $date_opened && $date_opened >= $three_years_ago) {

                    // Check for partial matches in the status description
                    foreach ($status_counts as $key => &$count) {
                        if (stripos($accountStatus, $key) !== false) {
                            $count++;
                            break;
                        }
                    }
                }
            }
        }
            $response['six_mon_max'] = $max_dpd_days_6m;

            $response['twelve_mon_max'] = $max_dpd_days_12m;

            $response['three_mon_max'] = $max_dpd_days_3m;

    }else{
            $accountType = [1   => "AUTO LOAN", 2   => "HOUSING LOAN", 3   => "PROPERTY LOAN", 4   => "LOAN AGAINST SHARES/SECURITIES", 5   => "PERSONAL LOAN", 6   => "CONSUMER LOAN", 7   => "GOLD LOAN", 8   => "EDUCATIONAL LOAN", 9   => "LOAN TO PROFESSIONAL", 10  => "CREDIT CARD", 11  => "LEASING", 12  => "OVERDRAFT", 13  => "TWO-WHEELER LOAN", 14  => "NON-FUNDED CREDIT FACILITY", 15  => "LOAN AGAINST BANK DEPOSITS", 16  => "FLEET CARD", 17  =>  "Commercial Vehicle Loan", 18  =>  "Telco – Wireless", 19  =>  "Telco – Broadband", 20  =>  "Telco – Landline", 23  =>  "GECL Secured", 24  =>  "GECL Unsecured", 31  =>  "Secured Credit Card", 32  =>  "Used Car Loan", 33  =>  "Construction Equipment Loan", 34  =>  "Tractor Loan", 35  =>  "Corporate Credit Card", 36  =>  "Kisan Credit Card", 37  =>  "Loan on Credit Card", 38  =>  "Prime Minister Jaan Dhan Yojana - Overdraft", 39  =>  "Mudra Loans – Shishu / Kishor / Tarun", 40  =>  "Microfinance – Business Loan", 41  =>  "Microfinance – Personal Loan", 42  =>  "Microfinance – Housing Loan", 43  =>  "Microfinance – Others", 44  =>  "Pradhan Mantri Awas Yojana - Credit Link Subsidy Scheme MAY CLSS", 45  =>  "P2P Personal Loan", 46  =>  "P2P Auto Loan", 47  =>  "P2P Education Loan", 51  =>  "BUSINESS LOAN – GENERAL", 52  =>  "BUSINESS LOAN –PRIORITY SECTOR – SMALL BUSINESS", 53  =>  "BUSINESS LOAN –PRIORITY SECTOR – AGRICULTURE", 54  =>  "BUSINESS LOAN –PRIORITY SECTOR – OTHERS", 55  =>  "BUSINESS NON-FUNDED CREDIT FACILITY – GENERAL", 56  =>  "BUSINESS NON-FUNDED CREDIT FACILITY – PRIORITY SECTOR – SMALL BUSINESS", 57  =>  "BUSINESS NON-FUNDED CREDIT FACILITY – PRIORITY SECTOR – AGRICULTURE", 58  =>  "BUSINESS NON-FUNDED CREDIT FACILITY – PRIORITY SECTOR – OTHERS", 59  =>  "BUSINESS LOANS AGAINST BANK DEPOSITS", 60  =>  "Staff Loan", 61  =>  "Business Loan - Unsecured", 0  =>  "Others"];
            $accountStatusCode = [00   => "No Suit Filed", 89   => "Wilful default", 93   => "Suit Filed(Wilful default)", 97   => "Suit Filed(Wilful Default) and Written-off", 30   => "Restructured", 31   => "Restructured Loan (Govt. Mandated)", 32   => "Settled", 33   => "Post (WO) Settled", 34   => "Account Sold", 35   => "Written Off and Account Sold", 36   => "Account Purchased", 37   => "Account Purchased and Written Off", 38   => "Account Purchased and Settled", 39   => "Account Purchased and Restructured", 40   => "Status Cleared", 41   => "Restructured Loan", 42   => "Restructured Loan (Govt. Mandated)", 43   => "Written-off", 44   => "Settled", 45   => "Post (WO) Settled", 46   => "Account Sold", 47   => "Written Off and Account Sold", 48   => "Account Purchased", 49   => "Account Purchased and Written Off", 50   => "Account Purchased and Settled", 51   => "Account Purchased and Restructured", 52   => "Status Cleared", 53   => "Suit Filed", 54   => "Suit Filed and Written-off", 55   => "Suit Filed and Settled", 56   => "Suit Filed and Post (WO) Settled", 57   => "Suit Filed and Account Sold", 58   => "Suit Filed and Written Off and Account Sold", 59   => "Suit Filed and Account Purchased", 60   => "Suit Filed and Account Purchased and Written Off", 61   => "Suit Filed and Account Purchased and Settled", 62   => "Suit Filed and Account Purchased and Restructured", 63   => "Suit Filed and Status Cleared", 64   => "Wilful Default and Restructured Loan", 65   => "Wilful Default and Restructured Loan (Govt. Mandated)", 66   => "Wilful Default and Settled", 67   => "Wilful Default and Post (WO) Settled", 68   => "Wilful Default and Account Sold", 69   => "Wilful Default and Written Off and Account Sold", 70   => "Wilful Default and Account Purchased", 72   => "Wilful Default and Account Purchased and Written Off", 73   => "Wilful Default and Account Purchased and Settled", 74   => "Wilful Default and Account Purchased and Restructured", 75   => "Wilful Default and Status Cleared", 76   => "Suit filed (Wilful default) and Restructured", 77   => "Suit filed (Wilful default) and Restructured Loan (Govt. Mandated)", 79   => "Suit filed (Wilful default) and Settled", 81   => "Suit filed (Wilful default) and Post (WO) Settled", 85   => "Suit filed (Wilful default) and Account Sold", 86   => "Suit filed (Wilful default) and Written Off and Account Sold", 87   => "Suit filed (Wilful default) and Account Purchased", 88   => "Suit filed (Wilful default) and Account Purchased and Written Off", 94   => "Suit filed (Wilful default) and Account Purchased and Settled", 90  => "Suit filed (Wilful default) and Account Purchased and Restructured",91   => "Suit filed (Wilful default) and Status Cleared",13   => "CLOSED",14   => "CLOSED",15   => "CLOSED",16   => "CLOSED",17   => "CLOSED",12   => "CLOSED",11   => "ACTIVE",71   => "ACTIVE",78   => "ACTIVE",80   => "ACTIVE",82   => "ACTIVE", 83   => "ACTIVE", 84   => "ACTIVE", 21   => "ACTIVE", 22   => "ACTIVE", 23   => "ACTIVE", 24   => "ACTIVE", 25   => "ACTIVE", 131  => "Restructured due to natural calamity",130  => "Restructured due to COVID-19"];

            $foir = FOIR::where('application_id', $application_id)->whereNull('deleted_at')->get();

            $report_data = json_decode($report);
            $data = $report_data->Body->ProcessResponse->Out->INProfileResponse->CAIS_Account->CAIS_Account_DETAILS ?? null;
            $enquiry_data = $report_data->Body->ProcessResponse->Out->INProfileResponse->CAPS->CAPS_Application_Details ?? "";
            if (is_array($data) && isset($data[0])) {
                $accountsSummary = $data;
            } else {
                $accountsSummary[] = $data;
            }

            foreach ($accountsSummary as $accounts) {
                if (isset($accounts->CAIS_Account_History) && is_array($accounts->CAIS_Account_History)) {
                    foreach ($accounts->CAIS_Account_History as $key => $account_history) {

                        if (isset($accounts->Highest_Credit_or_Original_Loan_Amount) && $accounts->Highest_Credit_or_Original_Loan_Amount != 0 && $accounts->Highest_Credit_or_Original_Loan_Amount != "") {
                            $approvedamount = $accounts->Highest_Credit_or_Original_Loan_Amount;
                        } else {
                            $approvedamount = 0;
                        }
                        $dpd_data = $accounts->CAIS_Account_History;
                        // 6 month DPD
                        $i = 0;
                        $six_mon = 0;
                        $monthSkip1 = 0;
                        foreach($dpd_data as $item){
                            $y = substr($item->Year, 2,3);
                            $monthSkip1 = $item->Month ?? (int)$monthSkip1 - 1;
                            $m = isset($item->Month) ? (strlen($item->Month) == 1 ? '0'.$item->Month : $item->Month) : $monthSkip1;
                            $loop_date = date('Y-m-d', strtotime($y . '-' . $m . "-01"));

                            if ($this->check_in_range($six_month, $current_date, $loop_date)) {

                                if($item->Days_Past_Due != null && $item->Days_Past_Due !== "0"){
                                    $six_mon = $six_mon + 1;
                                    if($max_dpd_days_6m < $item->Days_Past_Due){
                                        $max_dpd_days_6m = (int)$item->Days_Past_Due;
                                    }
                                    if($max_30_plus_dpd_6m < $item->Days_Past_Due && $max_30_plus_dpd_6m_count < $item->Days_Past_Due){
                                        $max_30_plus_dpd_6m_count = (int)$item->Days_Past_Due;
                                    }
                                }
                            }
                                $i = $i + 1 ;
                                 if($i == 6){
                                    break;
                                }

                        }
                        // 12 month DPD
                        $i = 0;
                        $twelve_mon = 0;
                        $monthSkip2 = 0;
                        foreach($dpd_data as $item){
                            $y = substr($item->Year, 2,3);
                            $monthSkip2 = isset($item->Month) ? $item->Month : (int)$monthSkip2 - 1;
                            $m = isset($item->Month) ? (strlen($item->Month) == 1 ? '0'.$item->Month : $item->Month) : $monthSkip2;
                            $loop_date = date('Y-m-d', strtotime($y . '-' . $m . "-01"));

                            if ($this->check_in_range($twelve_month, $current_date, $loop_date)) {

                                if($item->Days_Past_Due != null && $item->Days_Past_Due !== "0"){
                                    $twelve_mon = $twelve_mon + 1;
                                    if($max_dpd_days_12m < $item->Days_Past_Due){
                                        $max_dpd_days_12m = (int)$item->Days_Past_Due;
                                    }
                                    if($max_90_plus_dpd_12m <= $item->Days_Past_Due && $max_90_plus_dpd_12m_count < $item->Days_Past_Due ){
                                        $max_90_plus_dpd_12m_count = (int)$item->Days_Past_Due;
                                    }
                                }
                            }
                                $i = $i + 1 ;
                                if($i == 12){
                                    break;
                                }
                        }
                        // 3 month DPD
                        $i = 0;
                        $three_mon = 0;
                        $monthSkip3 = 0;
                        foreach($dpd_data as $item){
                            $y = substr($item->Year, 2,3);
                            $monthSkip3 = isset($item->Month) ? $item->Month : (int)$monthSkip3 - 1;
                            $m = isset($item->Month) ? (strlen($item->Month) == 1 ? '0'.$item->Month : $item->Month) : $monthSkip3;
                            $loop_date = date('Y-m-d', strtotime($y . '-' . $m . "-01"));

                            if ($this->check_in_range($three_month, $current_date, $loop_date)) {

                                if($item->Days_Past_Due != null && $item->Days_Past_Due !== "0"){
                                    $three_mon = $three_mon + 1;
                                    if($max_dpd_days_3m < $item->Days_Past_Due){
                                        $max_dpd_days_3m = (int)$item->Days_Past_Due;
                                    }
                                    if($max_0_plus_dpd_3m <= $item->Days_Past_Due && $max_0_plus_dpd_3m_count < $item->Days_Past_Due){
                                        $max_0_plus_dpd_3m_count = (int)$item->Days_Past_Due;
                                    }
                                }
                            }
                                $i = $i + 1 ;
                                if($i == 3){
                                    break;
                                }
                        }

                        $account_type = isset($accounts->Account_Type) && array_key_exists((int)$accounts->Account_Type, $accountType) ? ucwords(strtolower($accountType[(int)$accounts->Account_Type])) : '';
                        $account_status = isset($accounts->Account_Status) && array_key_exists((int)$accounts->Account_Status, $accountStatusCode) ? $accountStatusCode[(int)$accounts->Account_Status] : '';
                        $principal_write_off = isset($accounts->Written_Off_Amt_Principal) ? $accounts->Written_Off_Amt_Principal : '';
                        if($principal_write_off == "0"){
                            $principal_write_off = "";
                        }
                        $dateOpened = \Carbon\Carbon::parse($accounts->Open_Date)->format('Y-m-d') ?? '';
                        $response[$account_type][$dateOpened][$approvedamount]['AccountStatus'] = $account_status;
                        $response[$account_type][$dateOpened][$approvedamount]['PrincipalWriteOff'] = $principal_write_off;

                        $response[$account_type][$dateOpened][$approvedamount]['six_mon'] = $six_mon;
                        $response['six_mon_max'] = $max_dpd_days_6m;
                        $response['six_mon_max_30_plus'] = $max_30_plus_dpd_6m_count;

                        $response[$account_type][$dateOpened][$approvedamount]['twelve_mon'] = $twelve_mon;
                        $response['twelve_mon_max'] = $max_dpd_days_12m;
                        $response['twelve_mon_max_90_plus'] = $max_90_plus_dpd_12m_count;

                        $response[$account_type][$dateOpened][$approvedamount]['three_mon'] = $three_mon;
                        $response['three_mon_max'] = $max_dpd_days_3m;
                        $response['three_mon_max_0_plus'] = $max_0_plus_dpd_3m_count;

                        $response['enquiries'] = $enquiry_data;
                        $account_payment_status = [];
                        foreach($foir as $value){
                            if(strtolower($value->AccountType) == strtolower($account_type) && $value->ApprovedAmount == $accounts->Highest_Credit_or_Original_Loan_Amount && $value->Balance == $accounts->Current_Balance){
                                $account_payment_status = substr($value->dpd, strpos($value->dpd, '"') + 1, strpos($value->dpd, '"') + 1);
                            }
                        }

                        if (in_array($account_payment_status, $payment_status)) {
                            $year = substr($account_history->Year, 2,3);
                            $month = strlen($account_history->Month) == 1 ? '0'.$account_history->Month : $account_history->Month;
                            $DateOpened = \Carbon\Carbon::parse($accounts->Open_Date)->format('d-m-Y');
                            $accounthistory['@key'] = date('Y-m-d', strtotime($year . '-' . $month . "-01"));
                            if ($this->check_in_range($six_month, $current_date, $accounthistory['@key'])) {
                                if (isset($response[$account_type][$DateOpened][$approvedamount]['six']['dpd'])) {
                                    $response[$account_type][$DateOpened][$approvedamount]['six']['dpd'] = $response[$account_type][$DateOpened][$approvedamount]['six']['dpd'] + 1;
                                } else {
                                    $response[$account_type][$DateOpened][$approvedamount]['six']['dpd'] = 1;
                                }
                            }
                            if ($this->check_in_range($twelve_month, $current_date, $accounthistory['@key'])) {
                                if (isset($response[$account_type][$DateOpened][$approvedamount]['twelve']['dpd'])) {
                                    $response[$account_type][$DateOpened][$approvedamount]['twelve']['dpd'] = $response[$account_type][$DateOpened][$approvedamount]['twelve']['dpd'] + 1;
                                } else {
                                    $response[$account_type][$DateOpened][$approvedamount]['twelve']['dpd'] = 1;
                                }
                            }
                        }
                    }
                }
                // Retrieve the Open_Date and convert it if necessary
                $open_date = isset($accounts->Open_Date) ? $accounts->Open_Date : null;

                $accountStatus = isset($accounts->Account_Status) ? $accounts->Account_Status : null;

                // Check if the account is active (Date_Closed is null)
                if (isset($accounts)) {
                    if (is_null($accounts->Date_Closed) && isset($accountStatus)) {
                        // Get the status name based on the Account_Status code
                        $statusName = $accountStatusCode[$accountStatus] ?? null;

                        // Check if the status name includes "Restructured" and exclude "Restructured due to COVID-19"
                        if ($statusName && strpos($statusName, 'Restructured') !== false && $statusName !== 'Restructured due to COVID-19') {
                            $totalActiveRestructuredLoans++;
                        }
                    }
                }

                // Compare the Open_Date with the date from 36 months ago
                if (isset($open_date) && $open_date && $open_date >= $three_years_ago) {
                    // Get the account status description based on the status code
                    $account_status = isset($accounts->Account_Status) && array_key_exists((int)$accounts->Account_Status, $accountStatusCode) ? $accountStatusCode[(int)$accounts->Account_Status] : '';

                    // Check for partial matches in the status description
                    foreach ($status_counts as $key => &$count) {
                        if (stripos($account_status, $key) !== false) {
                            $count++;
                            break;
                        }
                    }
                }
            }

        }
        // Calculate the sum of all the tracked statuses
        $total_accounts_in_status = array_sum($status_counts);
        $response['total_accounts_in_status'] = $total_accounts_in_status;
        $response['totalActiveRestructuredLoans'] = $totalActiveRestructuredLoans;

        return $response;
    }

    function check_in_range($start_date, $end_date, $date_from_user)
    {
        // Convert to timestamp
        $start_ts = strtotime($start_date);
        $end_ts = strtotime($end_date);
        $user_ts = strtotime($date_from_user);

        // Check that user date is between start & end
        return (($user_ts >= $start_ts) && ($user_ts <= $end_ts));
    }

    public function getGeocodingDataFromAddress($address){
        try {
            $apiData = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address=' . urlencode($address['address']) . '&key=AIzaSyBJ5sOPcuh4edXH5KgE3vKqeZCfyO9JlHY');
            $apiData = json_decode($apiData);
            if ($apiData->status == "OK") {
                if (isset($apiData->results)) {
                    foreach ($apiData->results as $result) {
                        if (isset($result->geometry) && isset($result->geometry->location)) {
                            if (isset($result->geometry->location->lat) && isset($result->geometry->location->lng)) {
                                return ['lat' => $result->geometry->location->lat, 'lng' => $result->geometry->location->lng, 'pincode' => $address['pincode']];
                            }
                        }
                    }
                }
            }
            return false;
        }catch (\Exception $e){
            return false;
        }
    }

    public function getNearByMetro($lat, $lng){
        try {
            $apiData = file_get_contents('https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=' . $lat . ',' . $lng . '&key=AIzaSyBJ5sOPcuh4edXH5KgE3vKqeZCfyO9JlHY&rankby=distance&type=train_station');
            $apiData = json_decode($apiData);
            if ($apiData->status == "OK") {
                if (isset($apiData->results)) {
                    foreach ($apiData->results as $result) {
                        if (isset($result->geometry) && isset($result->geometry->location)) {
                            if (isset($result->geometry->location->lat) && isset($result->geometry->location->lng)) {
                                return ['lat' => $result->geometry->location->lat, 'lng' => $result->geometry->location->lng, 'name' => $result->name, 'response' => $apiData];
                            }
                        }
                    }
                }
            }
            return false;
        }catch (\Exception $e){
            return false;
        }
    }

    public function tracker(Request $request)
    {

        $data['user_id'] = $request->has('user_id') ? $request->get('user_id') : 29;
        $data['from_date'] = ($request->has('from_date') && !empty($request->get('from_date'))) ? Carbon::createFromFormat('Y-m-d', $request->get('from_date'))->startOfDay()->toDateTimeString() : Carbon::now()->startOfDay()->toDateTimeString();
        $data['to_date'] = ($request->has('to_date') && !empty($request->get('to_date'))) ? Carbon::createFromFormat('Y-m-d', $request->get('to_date'))->endOfDay()->toDateTimeString() : Carbon::now()->endOfDay()->toDateTimeString();
        $locations = Locations::orderBy('created_at', 'asc')
            ->where('created_at', '>=', $data['from_date'])->where('created_at', '<=', $data['to_date'])
            ->where('user_id', $data['user_id'])
            ->get();
        $lats = [];
        $lat1 = '';
        $lng1 = '';
        $distance_covered = 0;
        $duration_covered = 0;
        foreach ($locations as $index => $location) {
            if (!$index) {
                $data['center_lat'] = (float)$location->latitude;
                $data['center_lng'] = (float)$location->longitude;

                $lat1 = $data['center_lat'];
                $lng1 = $data['center_lng'];
            }

            $lats[] = [
                'lat' => (float)$location->latitude,
                'lng' => (float)$location->longitude,
                'date' => date('Y-m-d H:i:s', strtotime($location->created_at))
            ];


            if (isset($locations[$index + 1])) {
                $first_lat = (float)$location->latitude;
                $first_lng = (float)$location->longitude;
                $second_lat = (float)$locations[$index + 1]->latitude;
                $second_lng = (float)$locations[$index + 1]->longitude;

                $km = $this->getDistanceDetail(['lat' => $first_lat, 'lng' => $first_lng], ['lat' => $second_lat, 'lng' => $second_lng]);
                if (!is_nan($km)) {
                    $distance_covered += $km;
                    $meter = $km * 1000;

                    $time = (strtotime($locations[$index + 1]->created_at) - strtotime($location->created_at));
                    if ($time) {
                        $duration_covered += $meter / $time;

                    }
                }
            }
        }

        if ($lats) {
            $lat2 = $lats[count($lats) - 1]['lat'];
            $lng2 = $lats[count($lats) - 1]['lng'];
            $desLatLong = $lat2 . ',' . $lng2;
            $apiData = file_get_contents('https://maps.googleapis.com/maps/api/distancematrix/json?origins=' . $lat1 . ',' . $lng1 . '&destinations=' . $desLatLong . '&mode=driving&language=en-EN&sensor=false&key=AIzaSyA6u_3b3LBX_tNgJzCqkaSlmMfBSisMAuw');
            $apiData = json_decode($apiData);

            $distance = 0;
            $duration = 0;
            if (isset($apiData->rows)) {
                foreach ($apiData->rows as $row) {
                    foreach ($row->elements as $element) {
                        foreach ($element as $key => $item) {
                            if ($key == 'distance') {
                                $distance = $item->text;
                            } else if ($key == 'duration') {
                                $duration = $item->text;
                            }
                        }
                    }
                }
            }

            $data['places'] = [
                'destination' => array_map(function ($item) {
                    return $item;
                }, $apiData->destination_addresses),
                'origin' => array_map(function ($item) {
                    return $item;
                }, $apiData->origin_addresses),
                'distance' => round($distance_covered, 2) . ' Km',//$distance,
                'duration' => round($duration_covered / 60, 2) . ' Hr',//$duration,
                'distance_covered' => $distance_covered
            ];
        }

        $data['stops'] = $this->calculateStops($lats);
        $data['current_location_status'] = User::where('id', $data['user_id'])->first(['is_gps_on']);
        $data['gps_status'] = GPSLogs::where('user_id', $data['user_id'])->where('created_at', '>=', $data['from_date'])->where('created_at', '<=', $data['to_date'])->get();
        $data['locations'] = $lats;
        $data['center_lat'] = isset($data['center_lat']) ? $data['center_lat'] : 0;
        $data['center_lng'] = isset($data['center_lng']) ? $data['center_lng'] : 0;
        if ($request->has('bot')) {
            return $data;
        }
        $data['users'] = User::where('user_type', '>=', 5)->get(['id', 'name']);
        return view('admin.tracker', $data);
    }

    function Get_Address_From_Google_Maps($lat, $lon)
    {

        $url = "https://maps.googleapis.com/maps/api/geocode/json?key=AIzaSyBHVvDZIz9KzVEEC155az7swkSmTkyVpxo&latlng=$lat,$lon&sensor=false";

        $data = @file_get_contents($url);

        $jsondata = json_decode($data, true);

        if (!$this->check_status($jsondata)) return array();

        $address = array(
            'country' => $this->google_getCountry($jsondata),
            'province' => $this->google_getProvince($jsondata),
            'city' => $this->google_getCity($jsondata),
            'street' => $this->google_getStreet($jsondata),
            'postal_code' => $this->google_getPostalCode($jsondata),
            'country_code' => $this->google_getCountryCode($jsondata),
            'formatted_address' => $this->google_getAddress($jsondata),
        );

        return $address;
    }

    function check_status($jsondata)
    {
        if ($jsondata["status"] == "OK") return true;
        return false;
    }

    function google_getCountry($jsondata)
    {
        return $this->Find_Long_Name_Given_Type("country", $jsondata["results"][0]["address_components"]);
    }

    function google_getProvince($jsondata)
    {
        return $this->Find_Long_Name_Given_Type("administrative_area_level_1", $jsondata["results"][0]["address_components"], true);
    }

    function google_getCity($jsondata)
    {
        return $this->Find_Long_Name_Given_Type("locality", $jsondata["results"][0]["address_components"]);
    }

    function google_getStreet($jsondata)
    {
        return $this->Find_Long_Name_Given_Type("street_number", $jsondata["results"][0]["address_components"]) . ' ' . $this->Find_Long_Name_Given_Type("route", $jsondata["results"][0]["address_components"]);
    }

    function google_getPostalCode($jsondata)
    {
        return $this->Find_Long_Name_Given_Type("postal_code", $jsondata["results"][0]["address_components"]);
    }

    function google_getCountryCode($jsondata)
    {
        return $this->Find_Long_Name_Given_Type("country", $jsondata["results"][0]["address_components"], true);
    }

    function google_getAddress($jsondata)
    {
        return $jsondata["results"][0]["formatted_address"];
    }

    function Find_Long_Name_Given_Type($type, $array, $short_name = false)
    {
        foreach ($array as $value) {
            if (in_array($type, $value["types"])) {
                if ($short_name)
                    return $value["short_name"];
                return $value["long_name"];
            }
        }
    }

    public function calculateStops($coordinates)
    {
        $stops = [];
        $stop = true;
        foreach ($coordinates as $next => $coordinate) {
            if (isset($coordinates[$next + 1])) {
                if ($stop) {
                    $origin = ['lat' => $coordinate['lat'], 'lng' => $coordinate['lng']];
                }
                $dLat = $coordinates[$next + 1]['lat'];
                $dLng = $coordinates[$next + 1]['lng'];
                $dDate = $coordinates[$next + 1]['date'];
                $destination = ['lat' => $dLat, 'lng' => $dLng];
                if ($km = $this->getDistanceDetail($origin, $destination)) {
                    $meter = $km * 1000;

                    $time = (strtotime($dDate) - strtotime($coordinate['date']));
                    if ($time) {
                        $speed_mps = $meter / $time;
                        $speed_mpm = ($meter / $time) * 60;
                        $speed_mph = ($speed_mps * 3600.0);
                        if ($meter > 50 && $speed_mpm > 10) {
                            $stops[] = ['origin' => $origin, 'destination' => $destination, 'distance' => $meter, 'speed_mpm' => $speed_mpm, 'date' => date('Y-m-d H:i:s', strtotime($coordinate['date']))];
                            $stop = true;
                        }
                    }
                } else {
                    $stop = false;
                }
            }
        }

        return $stops;
    }

    public static function getDistanceDetail($LatLong, $desLatLong)
    {

        $lat1 = $LatLong['lat'];
        $log1 = $LatLong['lng'];

        $lat2 = $desLatLong['lat'];
        $log2 = $desLatLong['lng'];


        $dist = (((acos(sin(($lat1 * pi() / 180)) * sin(($lat2 * pi() / 180)) + cos(($lat1 * pi() / 180)) *
                    cos(($lat2 * pi() / 180)) * cos((($log1 - $log2) * pi() / 180)))) * 180 / pi()) * 60 * 1.1515);

        $dist = $dist * 1.609344;
        $distance = round($dist, 2);
        return $distance;

    }

    public function getPanValidation($id, $applicant_type)
    {
        try {
            $panVendor = CreditReport::where('application_id',$id)->where('applicant_type',$applicant_type)->first(['panVendor']);
            $applicant_type = ($applicant_type == 1) ? '' : '_'.$applicant_type;
            if($panVendor['panVendor'] == "decentro"){
                $file_path = $id.'/'.$id.'_response_pan_valid_decentro'.$applicant_type.'.json';
                $s3 = Storage::disk('s3');
                if ($s3->exists($file_path)) {
                    $file = $s3->get($file_path);
                    if (false !== $report_data = json_decode($file, true)) {
                        return $report_data;
                    }
                }
            }else{
                $file_path = $id.'/'.$id.'_response_pan_valid'.$applicant_type.'.json';
                $file = Equifax::readFile($file_path);
                if (false !== $report_data = json_decode($file, true)) {
                    return $report_data['soapenv:Envelope']['soapenv:Body']['sch:InquiryResponse'];
                }
            }
            return false;
        } catch (\Exception $e) {
            return false;
        }
    }

    public function getCibilReport($id, $applicant_type, $type = '',$bureauUrl=false)
    {
        $data = array();
        $data['is_home'] = true;
        try {
            $hashids = new Hashids('Creditfair by CS', 20);
            try {
                $id = $hashids->decode($id)[0];
            }catch (\Exception $e){

            }
            $applicant_type = (empty($applicant_type) || $applicant_type == 1) ? '' : '_'.$applicant_type;
            $type = $type.$applicant_type;
            $file_path = ($type != '_merchant') ? $id.'/'.$id . '_response' . $type . '.json' : 'merchant/'. $id.'/'.$id . '_response' . $type . '.json';
            if (false !== $file = Equifax::readFile($file_path)) {
                $report_data = json_decode($file, true);
//                return $report_data;
                //return $report_data['soapenv:Envelope']['soapenv:Body']['sch:InquiryResponse'];
                if(isset($report_data['soapenv:Envelope']) && isset($report_data['soapenv:Envelope']['soapenv:Body']['sch:InquiryResponse'])) {
                    $data['report_data'] = $report_data['soapenv:Envelope']['soapenv:Body']['sch:InquiryResponse'];
                    if ($this->isInternal) {
                        return $data;
                    }
                    $view = view('front.cibil-report', $data);
                }else {
                    $report_data = json_decode($file);
//                    $report = json_encode($report_data['Body']['ProcessResponse']['Out']['INProfileResponse']);
                    $report = $report_data->Body->ProcessResponse->Out->INProfileResponse;
                    $data = [
                        'id' => $report_data->ID ?? '',
                        'user_id' => $report_data->UserID ?? '',
                        'applicant_type' => $report_data->ApplicantType ?? 1,
                        'header' => $report->Header ?? '',
                        'applicant_details' => $report->CurrentApplication->Current_Application_Details ?? '',
                        'account_details' => $report->CAIS_Account ?? '',
                        'credit_caps' => $report->CAPS->CAPS_Summary ?? '',
                        'credit_caps_details' => $report->CAPS->CAPS_Application_Details ?? '',
                        'non_credit_caps' => $report->NonCreditCAPS->NonCreditCAPS_Summary ?? '',
                        'non_credit_caps_details' => $report->NonCreditCAPS->CAPS_Application_Details ?? '',
                        'score' => $report->SCORE ?? '',
                        'error' => $report_data->Body->ProcessResponse->Out->INProfileResponse->UserMessage->UserMessageText ?? '',
                    ];

                    if ($this->isInternal) {
                        return $data;
                    }
                    $view = view('front.experian-report', $data);
                }
                $pdf = App::make('snappy.pdf.wrapper');
                $pdf->loadHTML($view)->setOption('encoding', 'UTF-8')->setPaper('a4')->setOrientation('portrait');
                $pdf->setOption('margin-bottom', 25);
                if($bureauUrl){
                    $path = storage_path() . '/BureauTempDoc/' . time() . '_' . uniqid();
                    $pdf->save($path);
                    return $path;
                }
                return $pdf->inline();
            } else {
                if($bureauUrl){
                    return false;
                }
                $this->isRedirect = true;
                return redirect()->back();
            }
        } catch (\Exception $e) {
//            return $e->getMessage().' '.$e->getFile().' '.$e->getLine();
            (new Slack(new Request(['title'=>'Bureau Report Error','fields'=>['Application ID'=>$id,'error'=>$e->getMessage(),'line'=>$e->getLine(),'trace'=>$e->getTraceAsString(),'application_id'=>$id], 'group' => Slack::$STAGE_TESTING])))->send();
            if($bureauUrl){
                return false;
            }
            Session::flash('error', 'Bureau Report Error, Please check the bureau report');
            $this->isRedirect = true;
            return redirect()->back();
        }


    }

    public function getSoftCibilReport($id, $applicant_type, $type = '',$bureauUrl=false)
    {
        $data = array();
        $data['is_home'] = true;
        try {
            $hashids = new Hashids('Creditfair by CS', 20);
            $id = $hashids->decode($id)[0];
            $file_path = $id.'/'.$id . '_response_experian_soft_'.$applicant_type.'.json';
            if (false !== $file = Equifax::readFile($file_path)) {
                $report_data = json_decode($file, true);
                if(isset($report_data['soapenv:Envelope']) && isset($report_data['soapenv:Envelope']['soapenv:Body']['sch:InquiryResponse'])) {
                    $data['report_data'] = $report_data['soapenv:Envelope']['soapenv:Body']['sch:InquiryResponse'];
                    if ($this->isInternal) {
                        return $data;
                    }
                    $view = view('front.cibil-report', $data);
                }else {
                    $report_data = json_decode($file);
                    $report = $report_data->Body->ProcessResponse->Out->INProfileResponse;
                    $data = [
                        'id' => $report_data->ID ?? '',
                        'user_id' => $report_data->UserID ?? '',
                        'applicant_type' => $report_data->ApplicantType ?? 1,
                        'header' => $report->Header ?? '',
                        'applicant_details' => $report->CurrentApplication->Current_Application_Details ?? '',
                        'account_details' => $report->CAIS_Account ?? '',
                        'credit_caps' => $report->CAPS->CAPS_Summary ?? '',
                        'credit_caps_details' => $report->CAPS->CAPS_Application_Details ?? '',
                        'non_credit_caps' => $report->NonCreditCAPS->NonCreditCAPS_Summary ?? '',
                        'non_credit_caps_details' => $report->NonCreditCAPS->CAPS_Application_Details ?? '',
                        'score' => $report->SCORE ?? '',
                        'error' => $report_data->Body->ProcessResponse->Out->INProfileResponse->UserMessage->UserMessageText ?? '',
                    ];

                    if ($this->isInternal) {
                        return $data;
                    }
                    $view = view('front.experian-report-soft', $data);
                }
                $pdf = App::make('snappy.pdf.wrapper');
                $pdf->loadHTML($view)->setOption('encoding', 'UTF-8')->setPaper('a4')->setOrientation('portrait');
                $pdf->setOption('margin-bottom', 25);
                if($bureauUrl){
                    $path = storage_path() . '/BureauTempDoc/' . time() . '_' . uniqid();
                    $pdf->save($path);
                    return $path;
                }
                return $pdf->inline();
            } else {
                if($bureauUrl){
                    return false;
                }
                Session::flash('error', 'Bureau Report is missing, Please generate the bureau');
                $this->isRedirect = true;
                return redirect()->back();
            }
        } catch (\Exception $e) {
//            return $e->getMessage().' '.$e->getFile().' '.$e->getLine();
            (new Slack(new Request(['title'=>'Failed to View Bureau Report','fields'=>['Application ID'=>$id,'error'=>$e->getMessage(),'line'=>$e->getLine(),'trace'=>$e->getTraceAsString(),'application_id'=>$id], 'group' => Slack::$STAGE_TESTING])))->send();
            if($bureauUrl){
                return false;
            }
            Session::flash('error', 'Failed to View Bureau Report, Please Check the bureau report');
            $this->isRedirect = true;
            return redirect()->back();
        }
    }

    public function getAllMandate($id)
    {
        $data['mandates'] = Mandate::where('consumer_application_id', $id)->get();
        $i = 0;
        foreach ($data['mandates'] as $mandate) {
            if ($mandate->collection == "D") {
                $data['mandates'][$i]['collection'] = "Debit Fix Amount";
            } elseif ($mandate->collection == "M") {
                $data['mandates'][$i]['collection'] = "Up to Maximum Amount";
            } else {
                $data['mandates'][$i]['collection'] = "Collection Not Selected";
            }
            if ($mandate->frequency == "M") {
                $data['mandates'][$i]['frequency'] = "Monthly";
            } elseif ($mandate->frequency == "H") {
                $data['mandates'][$i]['frequency'] = "Halfyrly";
            } elseif ($mandate->frequency == "Y") {
                $data['mandates'][$i]['frequency'] = "Yearly";
            } elseif ($mandate->frequency == "B") {
                $data['mandates'][$i]['frequency'] = "Bimonthly";
            } elseif ($mandate->frequency == "Q") {
                $data['mandates'][$i]['frequency'] = "Quarterly";
            } elseif ($mandate->frequency == "O") {
                $data['mandates'][$i]['frequency'] = "As and When Presented";
            } else {
                $data['mandates'][$i]['frequency'] = "Frequency Not Selected";
            }

            $data['mandates'][$i]['status'] = $mandate->status;//($mandate->umrn) ? 1 : ($mandate->status == 1 ? 0 : $mandate->status);

            $i++;
        }
        $data['application_id'] = $id;
        return view('admin.mandate.index', $data);
    }

    public function addMandate($id)
    {

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

    public function editMandate($id)
    {
        $mandate = Mandate::find($id);
        if (isset($mandate->umrn)) {
            //$mandate->status = ($mandate->umrn) ? 1 : ($mandate->status == 1 ? 0 : $mandate->status);
        }
        $data['mandate'] = $mandate;
        $data['application_id'] = $data['mandate']->consumer_application_id;
        $files = ConsumerApplicationFiles::where('consumer_application_id', $data['mandate']->consumer_application_id)->whereIn('file_type', ['nach_cancellation_proof_' . $id, 'nach_submitted_proof_' . $id])->orderBy('created_at', 'desc')->get();
        foreach ($files as $file) {
            if (isset($file->file_path)) {
                if ($file->file_type == 'nach_cancellation_proof_' . $id) {
                    $data['nach_cancellation_proof_file'] = $file;
                } else if ($file->file_type == 'nach_submitted_proof_' . $id) {
                    $data['nach_submitted_proof_file'] = $file;
                }
            }
        }
        $mandate_status_log = MandateStatusLog::where('mandate_id',$id)->where('status',$data['mandate']->status)->orderby('created_at','desc')->first();
        $data['mandate_status_reason'] = (isset($mandate_status_log) && isset($mandate_status_log->reason)) ? $mandate_status_log->reason : "";
        $data['logs'] = MandateLogs::with('user')->where('mandate_id', $id)->get();
        return view('admin.mandate.addMandate', $data);
    }

    public function saveMandate($id, Request $request)
    {
        $application = ConsumerApplication::where('id', $id)->whereNotNull('applicant_id')->first(['applicant_id']);
        $mandate = new Mandate();
        $mandate->fill($request->all());
        $mandate->consumer_application_id = $id;

        if ($request->has('until_cancelled') && $request->get('until_cancelled') == 'on'){
            $mandate->until_cancelled = 1;
            $final_collection_date = $this->calculateFinalCollectionDate($request, $id);
            $mandate->expiry_date = $final_collection_date;
        }else{
            $mandate->until_cancelled = 0;
        }
        $mandate->applicant_id = isset($application->applicant_id) ? $application->applicant_id : 0;
        $mandate->save();
        if ($request->hasFile('nach_cancellation_proof')) {
            $this->uploadSingleFile($mandate->consumer_application_id, 'nach_cancellation_proof_' . $mandate->id, $request->file('nach_cancellation_proof'), $request);
        }

        if ($request->hasFile('nach_submitted_proof')) {
            $this->uploadSingleFile($mandate->consumer_application_id, 'nach_submitted_proof_' . $mandate->id, $request->file('nach_submitted_proof'), $request);
        }

        if ($request->has('status') && $request->get('status') == 'rejected') {
            $rejection_message = $request->get('rejection_message');
            $this->alertCustomerForRejection($id, $rejection_message);
        }
        Session::flash('success', 'Mandate created successfully');
        return \redirect()->back();
    }

    public function updateMandateSingle($id, $data, $application_id)
    {
        $mandate = Mandate::find($id);

        MandateStatusLog::insert([
            'mandate_id' => $id,
            'user_id' => Auth::user()->id,
            'status' => $mandate->status,
            'reason' => $mandate->rejection_message,
            'created_at' => Carbon::now()->toDateTimeString()
        ]);

        $mandatelog = new MandateLogs();
        $mandatelog->fill($mandate->toarray());
        $mandatelog->mandate_id = $mandate->id;
        $mandatelog->created_at = Carbon::now()->toDateTimeString();
        $mandatelog->created_by = Auth::user()->id;
        $mandatelog->save();

        if(strtolower($data['mandate_status']) != 'rejected') {
            $mandate->umrn = $data['umrn'];
        }
        $mandate->status = strtolower($data['mandate_status']);
        $mandate->rejection_message = $data['rejection_reason'];
        $mandate->mandate_amount = $data['debit_amount_upto_max_amount'];

        if ($mandate->umrn && strtolower($data['mandate_status']) == 'accepted'){
            StatusLogs::insert([
                'application_id' => $application_id,
                'user_id' => 107,
                'status' => 'nach registered',
                'created_at' => Carbon::now()->toDateTimeString()
            ]);

            ConsumerApplication::where('id', $application_id)->update(['state' => 'nach registered']);
        }

        $mandate->save();

        if (strtolower($data['mandate_status']) == 'rejected') {
            $this->alertCustomerForRejection($application_id, $data['rejection_reason']);
        }
    }

    public function updateMandate($mandate_id, Request $request)
    {
        $previousMandateData = Mandate::where('id', $mandate_id)->first();
        $mandate = Mandate::find($mandate_id);
        $currentStatus = $mandate->status;
        $application_id = $mandate->consumer_application_id;

        $mandate->fill($request->all());

        if ($request->has('until_cancelled') && $request->get('until_cancelled') == 'on'){
            $mandate->until_cancelled = 1;
            $final_collection_date = $this->calculateFinalCollectionDate($request, $mandate->consumer_application_id);
            $mandate->expiry_date = $final_collection_date;

        }else{
            $mandate->until_cancelled = 0;
        }

        $mandate->save();
        $reason = "";

       // if($request->has('status') && ($request->get('status') == 'cancelled' || $request->get('status') == 'inactive') && $currentStatus != $request->get('status')){
            if($request->has('status') && ($request->get('status') == 'cancelled' || $request->get('status') == 'inactive') && $currentStatus != $request->get('status')){

                $reason = $request->get('reason_message');
        }

        if($request->has('status') && $request->get('status') == 'rejected' && $currentStatus != $request->get('status')){
            $reason = $request->get('rejection_message');
        }
        MandateStatusLog::insert([
            'mandate_id' => $mandate_id,
            'user_id' => Auth::user()->id,
            'status' => $mandate->status,
            'reason' => $reason,
            'created_at' => Carbon::now()->toDateTimeString()
        ]);
        if ($request->hasFile('nach_cancellation_proof')) {
            $this->uploadSingleFile($mandate->consumer_application_id, 'nach_cancellation_proof_' . $mandate_id, $request->file('nach_cancellation_proof'), $request);
        }

        if ($request->hasFile('nach_submitted_proof')) {
            $this->uploadSingleFile($mandate->consumer_application_id, 'nach_submitted_proof_' . $mandate_id, $request->file('nach_submitted_proof'), $request);
        }

        if ($request->has('status') && $request->get('status') == 'rejected' && $currentStatus != $request->get('status')) {
            $rejection_message = $request->get('rejection_message');
            $this->alertCustomerForRejection($application_id, $rejection_message);
        }

        (new MandateLogs())->lockPrevious($previousMandateData, $mandate_id, $request);

        Session::flash('success', 'Mandate updated successfully');
        return \redirect()->to('/admin/mandate/edit/' . $mandate_id);
    }

    public function calculateFinalCollectionDate($request, $application_id)
    {
        $emi = ApplicationEmiCalculation::where('application_id',$application_id)->first(['emi_date','remaining_emi']);
        if(isset($emi)){
            $first_emi_date = (isset($emi->emi_date) && $emi->emi_date != '') ? date('Y-m-d', strtotime($emi->emi_date)) : "";
            $last_emi_date = date('Y-m-d', strtotime("+" . ($emi->remaining_emi - 1) . " months", strtotime($emi->emi_date)));

            $last_emi_plus_36_months = date('Y-m-d', strtotime("+36 months", strtotime($last_emi_date)));
            $first_emi_plus_360_months = date('Y-m-d', strtotime("+360 months", strtotime($first_emi_date)));
            $final_date_collection_until_cancelled = min($last_emi_plus_36_months,$first_emi_plus_360_months);
            if($request->has('until_cancelled') && $request->get('until_cancelled') == 'on'){
                return $final_date_collection_until_cancelled;
            }
        }
        return null;
    }

    public function alertCustomerForRejection($application_id, $rejection_message)
    {
        $rejection_message = ($rejection_message) ? $rejection_message : '';
        $message = " due to " . $rejection_message;

        $application = ConsumerApplication::with('merchant', 'application_element.merchant_center')->where('id', $application_id)->first();

        $cc_emails = [];
        if (isset($application->application_element) && isset($application->application_element->merchant_center)) {
            if (isset($application->application_element->merchant_center->email)) {
                $cc_emails = explode(',',$application->application_element->merchant_center->email);
            }
        }

        $request = new Request();
        $request->request->add([
            'type' => 'Bank-Details',
            'bot' => true
        ]);
        $document = (new ConsumerDocument($request));
        $gstDetails = $document->getDocument($application_id);
        if ($gstDetails instanceof RedirectResponse){
            return true;
        }
        if (!empty($gstDetails['user']['email_for_merchant'])) {
            //array_push($cc_emails, $gstDetails['user']['email_for_merchant']);
            $cc_emails = array_merge($cc_emails, explode(',',$gstDetails['user']['email_for_merchant']));
        }

//        $cc_emails = array_merge($cc_emails, ['payments@creditfair.in']);
        $gstDetails['rejection_message'] = $message;
        $data = [
            'body' => view('emails.reject_nach_email', $gstDetails),
            'subject' => 'Urgent - Your Auto Debit Mandate request was Rejected'
        ];

        $to[] = $gstDetails['user']['customer_email'];
        if (_env('NOTIFY_EMAIL', '')) {
            //array_push($to, _env('NOTIFY_EMAIL', ''));
        }

        if (isset($gstDetails['user']['customer_email']) && !empty($gstDetails['user']['customer_email'])) {
            \Mail::send('emails.blank', [
                'body' => $data['body'],
            ], function ($message) use ($gstDetails, $data, $to, $cc_emails, $application) {
                $message->to($to)->subject($data['subject']);
                $message->cc(trim($cc_emails));
                if ($application->lender_id == 2) {
                    $message->attach(storage_path() . '/csv/KM_Updated_NACH.pdf', ['as' => 'Nach']);
                    $message->attach(storage_path() . '/csv/km_sample_nach.pdf', ['as' => 'Sample Nach']);
                } else {
                    $message->attach(storage_path() . '/csv/Pride NACH Form.pdf', ['as' => 'Nach']);
                    $message->attach(storage_path() . '/csv/pride_nach_sample.pdf', ['as' => 'Sample Nach']);
                }
            });
        }
    }

    public function fetchOnfidoReport(Request $request){
        if($request->has('id')){

            $jobs = CampaignsJobProvider::where('from','run_onfido')->where('application_id', $request->get('id'))->where('applicant_type', $request->get('applicant_type'))->where('is_available',0)->first(['id']);
            if(isset($jobs->id)){
                return \response()->json(['status' => 'FAIL','message' => 'Report is already in queue']);
            }

            $onfido = new OnfidoIntegration();
            $onfido->runOnfido($request->get('id'), $request->get('applicant_type'));
            return \response()->json(['status' => 'OK','message' => 'Report feteched']);
        }
        return \response()->json(['status' => 'FAIL','message' => 'Failed to fetch onfido report']);
    }

    public function waitReminder($application_id)
    {
        $jobProvider = JobProvider::where('application_id', $application_id)->where('from', 'applicationReminder')->first(['id']);
        if (!isset($jobProvider->id)) {

            $reminder = [5, 10, 15, 20];
            $application = ConsumerApplication::with('merchant')->where('id', $application_id)->first();
            $payload = [];
            foreach ($reminder as $time) {

                $name = 'Advisors';
                $user_id = 0;
                if ($time == 10) {
                    $name = 'Rohit';
                    $user_id = 519;
                } else if ($time == 15) {
                    $name = 'Piyush';
                    $user_id = 10;
                } else if ($time == 20) {
                    $name = 'Aditya';
                    $user_id = 26;
                }

                try{
                    $merchant_name = $application->merchant->merchant_name ?? '';
                    $subject = $time . ' minutes since ' . $application->name . '\'s application from ' . $merchant_name . ' was logged in';
                    $link = "https://creditfair.in/admin/consumer-applications/edit/" . $application_id;
                    // for slack notification
                    $linkInfo = ($time == 20) ? $link : null;
                    $body = 'Dear ' . $name . ',<br/> It has been ' . $time . ' minutes since ' . $application->name . '\'s application from ' . $merchant_name . ' was logged in. Call the customer or merchant and put case in process ASAP <br/><br/> <a href="' . $link . '">Application Link</a>'.' '.$linkInfo;

                    $payload[] = [
                        'payload' => json_encode(['id' => $application_id, 'subject' => $subject, 'body' => $body, 'name' => $name, 'user_id' => $user_id, 'time' => $time]),
                        'from' => 'applicationReminder',
                        'application_id' => $application_id,
                        'available_at' => Carbon::now()->addMinutes(($time))->toDateTimeString(),
                        'created_at' => Carbon::now()->toDateTimeString()
                    ];
                } catch (\Exception $e) {}
            }
            if($payload){
                JobProvider::insert($payload);
            }
        }
    }

//    function getCIBILPaymentReport(Request $request)
//    {
//        if ($request->has('export')) {
//
//            if (!$request->has('job')) {
//
//                $jobsData = $request->all();
//                $payload[] = [
//                    'payload' => json_encode(array_merge($jobsData, ['job' => 1])),
//                    'from' => 'getCIBILPaymentReport',
//                    'application_id' => 23,
//                    'available_at' => Carbon::now()->toDateTimeString(),
//                    'created_at' => Carbon::now()->toDateTimeString()
//                ];
//
//                JobProvider::insert($payload);
//
//                \Session::flash('success', 'You\'ll receive the file shortly on your mail');
//                $lenders = Lenders::get();
//                return view('admin.reports.bureau_payment', ['lenders' => $lenders]);
//            }
//            ini_set('max_execution_time', -1);
//            set_time_limit(0);
//            ini_set('memory_limit', '-1');
//            $_from = $request->get('year') . '-' . ($request->get('month') + 1) . '-' . '01';
//            //$from = '2024-04-01 00:00:00';
//            //$to = '2024-04-10 23:59:59';
//            $_from = $request->get('year') . '-' . ($request->get('month') + 1) . '-' . '01';
//            $from = Carbon::createFromFormat('Y-m-d', $_from)->startOfMonth()->toDateTimeString();
//            $to = Carbon::createFromFormat('Y-m-d', $_from)->endOfMonth()->toDateTimeString();
//            $_from = date('dmY', strtotime($from));
//
//            $emiPayment = new LoanManagement();
//            //$emiPayment = new PaymentEmi();
//
//            $consumerDocument = (new ConsumerDocument($request));
//
//            $applications = ConsumerApplication::with('emi', 'proFormaInvoice', 'lender')->whereNull('is_deleted');
//            $lender_id = 0;
//            if ($request->has('lender_id') && !empty($request->get('lender_id'))) {
//                $applications = $applications->where('lender_id', $request->get('lender_id'));
//                $lender_id = $request->get('lender_id');
//            }
//            $applications = $applications->whereIn('state', ['disbursed', 'closed', 'nach registered', 'cancelled', 'cancellation in-process'])->groupBy('id')->get();
//
//            if ($lender_id > 0) {
//                $this->paymentData[] = ['Reporting Member ID', 'Short Name', 'Cycle Identification', 'Date Reported', 'Reporting Password', 'Authentication Method', 'Future Use', 'Member Data'];
//
//                $member = $this->getCibilMember($lender_id, $request);
//
//                $this->paymentData[] = ['code' => $member['code'], 'name' => $member['name'], '', date('dmY', strtotime("now")), '', '', '', ''];
//                $this->paymentData[] = ['', '', '', '', '', '', '', ''];
//                $this->paymentData[] = ['', '', '', '', '', '', '', ''];
//                $this->paymentData[] = ['', '', '', '', '', '', '', ''];
//
//            }
//
//            $this->paymentData[] = ['Consumer Name', 'Date of Birth',
//                'Gender', 'Income Tax ID Number', 'Passport Number', 'Passport Issue Date', 'Passport Expiry Date', 'Voter ID Number', 'Driving License Number',
//                'Driving License Issue Date', 'Driving License Expiry Date', 'Ration Card Number', 'Universal ID Number', 'Additional ID #1',
//                'Additional ID #2', 'Telephone No.Mobile', 'Telephone No.Residence', 'Telephone No.Office', 'Extension Office',
//                'Telephone No.Other', 'Extension Other', 'Email ID 1', 'Email ID 2', 'Address 1', 'State Code 1', 'PIN Code 1',
//                'Address Category 1', 'Residence Code 1', 'Address 2', 'State Code 2', 'PIN Code 2', 'Address Category 2', 'Residence Code 2',
//                'Current/New Member Code', 'Current/New Member Short Name', 'Curr/New Account No', 'Account Type', 'Ownership Indicator',
//                'Date Opened/Disbursed', 'Date of Last Payment', 'Date Closed', 'Date Reported', 'High Credit/Sanctioned Amt', 'Current  Balance',
//                'Amt Overdue', 'No of Days Past Due', 'Old Mbr Code', 'Old Mbr Short Name', 'Old Acc No', 'Old Acc Type', 'Old Ownership Indicator',
//                'Suit Filed / Wilful Default', 'Credit Facility Status', 'Asset Classification', 'Value of Collateral', 'Type of Collateral',
//                'Credit Limit', 'Cash Limit', 'Rate of Interest', 'RepaymentTenure', 'EMI Amount', 'Written- off Amount (Total)', 'Written- off Principal Amount',
//                'Settlement Amt', 'Payment Frequency', 'Actual Payment Amt', 'Occupation Code', 'Income', 'Net/Gross Income Indicator', 'Monthly/Annual Income Indicator'
//            ];
//
//
//            if(!$request->has('only_over_due')) {
//
//                $this->getCibilReportApplication = [];
//                foreach ($applications as $key => $application) {
//                    if ($application->emi) {
//                        if ($emi_date = $this->checkEMIDate($application, $from, $to)) {
//                            try {
//                                $emiTranaction = $emiPayment->getPaymentDueHistory($application->id, date('Y-m-d', strtotime($to)));
//                                $this->getDetailsOfPaymentsv1($application, $emiTranaction, $consumerDocument, $emi_date, $request);
//                                $this->getCibilReportApplication[] = $application->id;
//                            } catch (\Exception $e) {
//                                return $e->getMessage() . '|' . $e->getFile() . '|' . $e->getLine() . ' ID-' . $application->id;
//                            }
//                        }
//                    }
//                }
//
//
//                $this->getDelayedPaymentTransaction($from, $to, $emiPayment, $consumerDocument, $lender_id, $request);
//            }
//            if($request->has('with_over_due') || $request->has('only_over_due')) {
//                $this->getOverDuePayments($emiPayment, $consumerDocument, $request, $lender_id, $from);
//            }
//            $request = new Request(['data' => $this->paymentData, 'sheet' => 'Sheet1']);
//            //return Excel::download((new Exporter($request)), $request->get('bureau') . $from . '_to_' . $to . '.xls');
//
//            $fileName = ($member['code'] ?? '').'-Consumer-'.$_from.'-'.date('dmY', strtotime("now")).'-'.date('His', strtotime("now")).'.xls';
//
//            Excel::store((new BureauExporter($request)), $fileName);
//            // $file = time().$request->get('bureau') . $from . '_to_' . $to . '.xlsx';
//
//            // Excel::store((new Exporter($request)), $file);
//            // $path = (new CSV())->save($this->paymentData, time().$request->get('bureau') . $from . '_to_' . $to, null, 'csv');
//            $emails = _env('APP_CONNECTION') ? ['sunil@creditfair.in','imran@creditfair.in','sarah@creditfair.in'] : ['suyog@creditfair.in','sarah@creditfair.in'];
//
//            Mail::send('emails.reminders.basic_reminder',
//                ['body'=>'Bureau Report Data']
//                , function ($message) use ($fileName, $emails) {
//                    $message->to($emails)->subject('Bureau Report Data');
//                    //$message->cc(['imran@creditfair.in']);
//                    $message->attachData(file_get_contents(storage_path().'/app/'.$fileName), $fileName);
//                    // $message->attachData(file_get_contents($path), $path);
//            });
//            unlink(storage_path() . '/app/' . $fileName);
//
//            return true;
//        }
//
//        $lenders = Lenders::get();
//        return view('admin.reports.bureau_payment', ['lenders' => $lenders]);
//    }

    function getCIBILPaymentReportV1(Request $request)
    {
        $this->getCibilReportApplication = [];
        if ($request->has('export')) {
            ini_set('max_execution_time', -1);
            set_time_limit(0);
            ini_set('memory_limit', '-1');

            $from = Carbon::createFromFormat('Y-m-d', $request->get('from_date'))->startOfDay()->toDateTimeString();
            $to = Carbon::createFromFormat('Y-m-d', $request->get('to_date'))->endOfDay()->toDateTimeString();
            $_from = date('dmY', strtotime($from));
            $_to = date('dmY', strtotime($to));
            $sixMonthsAgo = Carbon::now()->subMonths(6);

            $emiPayment = new LoanManagement();
            $consumerDocument = new ConsumerDocument($request);

            $inActiveStates = ['closed', 'cancelled', 'cancellation in-process'];
            $activeStates = ['disbursed', 'nach registered'];
            $applicationStates = array_merge($activeStates, $inActiveStates);

            //TODO: Testing code to filter merchants
            /*$_cases = ConsumerApplication::where('merchant_id', 4696)->where('lender_id', 2)->whereNull('deleted_at')->whereIn('state', $applicationStates)->get()->toArray();
            $_casesIds = array_column($_cases, 'id');*/

            $inActiveApplications = StatusLogs::has('application')/*->whereIn('application_id', $_casesIds)*/->whereIn('status', $inActiveStates)->where('is_reversed', 0)->where('created_at', '>=', $sixMonthsAgo)->groupBy('application_id')->get(['application_id'])->toArray();
            $inActiveIds = array_column($inActiveApplications, 'application_id');
            $activeApplications = StatusLogs::has('activeApplication')/*->whereIn('application_id', $_casesIds)*/->whereIn('status', $activeStates)
                ->where('is_reversed', 0)
                ->groupBy('application_id')->get(['application_id'])->toArray();
            $activeIds = array_column($activeApplications, 'application_id');

            $applicationIds = array_unique(array_merge($activeIds, $inActiveIds));

            $lender_id = 0;
            if ($request->has('lender_id') && !empty($request->get('lender_id'))) {
                $lender_id = $request->get('lender_id');
            }

            if ($lender_id > 0) {
                $this->paymentData[] = ['Reporting Member ID', 'Short Name', 'Cycle Identification', 'Date Reported', 'Reporting Password', 'Authentication Method', 'Future Use', 'Member Data'];

                $member = $this->getCibilMember($lender_id, $request);

                $this->paymentData[] = ['code' => $member['code'], 'name' => $member['name'], '', date('dmY', strtotime("now")), '', '', '', ''];
                $this->paymentData[] = ['', '', '', '', '', '', '', ''];
                $this->paymentData[] = ['', '', '', '', '', '', '', ''];
                $this->paymentData[] = ['', '', '', '', '', '', '', ''];

            }

            $this->paymentData[] = ['Consumer Name', 'Date of Birth',
                'Gender', 'Income Tax ID Number', 'Passport Number', 'Passport Issue Date', 'Passport Expiry Date', 'Voter ID Number', 'Driving License Number',
                'Driving License Issue Date', 'Driving License Expiry Date', 'Ration Card Number', 'Universal ID Number', 'Additional ID #1',
                'Additional ID #2', 'Telephone No.Mobile', 'Telephone No.Residence', 'Telephone No.Office', 'Extension Office',
                'Telephone No.Other', 'Extension Other', 'Email ID 1', 'Email ID 2', 'Address 1', 'State Code 1', 'PIN Code 1',
                'Address Category 1', 'Residence Code 1', 'Address 2', 'State Code 2', 'PIN Code 2', 'Address Category 2', 'Residence Code 2',
                'Current/New Member Code', 'Current/New Member Short Name', 'Curr/New Account No', 'Account Type', 'Ownership Indicator',
                'Date Opened/Disbursed', 'Date of Last Payment', 'Date Closed', 'Date Reported', 'High Credit/Sanctioned Amt', 'Current  Balance',
                'Amt Overdue', 'No of Days Past Due', 'Old Mbr Code', 'Old Mbr Short Name', 'Old Acc No', 'Old Acc Type', 'Old Ownership Indicator',
                'Suit Filed / Wilful Default', 'Credit Facility Status', 'Asset Classification', 'Value of Collateral', 'Type of Collateral',
                'Credit Limit', 'Cash Limit', 'Rate of Interest', 'RepaymentTenure', 'EMI Amount', 'Written- off Amount (Total)', 'Written- off Principal Amount',
                'Settlement Amt', 'Payment Frequency', 'Actual Payment Amt', 'Occupation Code', 'Income', 'Net/Gross Income Indicator', 'Monthly/Annual Income Indicator'
            ];

            foreach(array_chunk($applicationIds,5000) as $idsData){
                $applications = ConsumerApplication::with('emi', 'proFormaInvoice', 'lender', 'merchant', 'application_element')
                    ->whereNull('is_deleted')->whereNotIn('merchant_id', [6478,7516,9421])->whereIn('id', $idsData);

                if($lender_id > 0) {
                    $applications = $applications->where('lender_id', $request->get('lender_id'));
                }

                $applications = $applications->whereIn('state', $applicationStates)->get();


                if(!$request->has('only_over_due')) {

                    foreach ($applications as $key => $application) {
                        if ($application->emi) {
                            if ($emi_date = $this->checkEMIDate($application, $from, $to)) {
                                try {
                                    $emiTranaction = $emiPayment->getPaymentDueHistory($application->id, date('Y-m-d', strtotime($to)));
                                    $this->getDetailsOfPaymentsv1($application, $emiTranaction, $consumerDocument, $emi_date, $request);
                                    $this->getCibilReportApplication[] = $application->id;
                                } catch (\Exception $e) {
                                    return $e->getMessage() . '|' . $e->getFile() . '|' . $e->getLine() . ' ID-' . $application->id;
                                }
                            }
                        }
                    }

                }
            }
            $this->getDelayedPaymentTransaction($from, $to, $emiPayment, $consumerDocument, $lender_id, $request);

            if($request->has('with_over_due') || $request->has('only_over_due')) {
                $this->getOverDuePayments($emiPayment, $consumerDocument, $request, $lender_id, $from);
            }

            $request = new Request(['data' => $this->paymentData, 'sheet' => 'Sheet1']);

            $fileName = ($member['code'] ?? '').'-Consumer-'.$_from.'-'.$_to.'-'.date('His', strtotime("now")).'.xls';

            Excel::store((new BureauExporter($request)), $fileName);
            $emails = _env('APP_CONNECTION') ? ['imran@creditfair.in', 'amol@creditfair.in', 'disha.doshi@creditfair.in'] : ['sunil@creditfair.in'];
            $cc_emails = _env('APP_CONNECTION') ? ['sunil@creditfair.in'] : ['sunil@creditfair.in'];

            Mail::send('emails.reminders.basic_reminder',
                ['body'=>'Bureau Report Data']
                , function ($message) use ($fileName, $emails, $cc_emails) {
                    $message->to($emails)->subject('Bureau Report Data');
                    $message->cc($cc_emails);
                    $message->attachData(file_get_contents(storage_path().'/app/'.$fileName), $fileName);
                    // $message->attachData(file_get_contents($path), $path);
            });
            unlink(storage_path() . '/app/' . $fileName);

            return true;
        }

        $lenders = Lenders::get();
        return view('admin.reports.bureau_payment', ['lenders' => $lenders]);
    }

    public function getOverDuePayments(LoanManagement $emiPayment, ConsumerDocument $consumerDocument, Request $request, $lender_id, $from){


        if ($lender_id == 0) {
            $lender_id = [1, 2];
        } else {
            $lender_id = [$lender_id];
        }

        $data = EmiPayment::whereHas('application', function ($query) use ($lender_id) {
            $query->whereIn('lender_id', $lender_id)->whereNull('is_deleted');
        })->with('application')
        ->with(['application_element' => function ($query) use ($lender_id) {
                $query->where('amount_over_due', '>', 0)->where('last_emi_date','<=',date('Y-m-d'));
        }])->whereNotIn('payment_status',['success'])->where('emi_date', '<', $from)->orderBy('emi_date','desc')->get();

        foreach ($data as $item) {
            if (isset($item->application) && isset($item->application->id) && in_array($item->application->state, ['disbursed', 'closed', 'nach registered', 'cancelled', 'cancellation in-process']) && !in_array($item->application_id, $this->getCibilReportApplication)) {
                $emiTranaction = $emiPayment->getPaymentDueHistory($item->application_id);
                $this->getDetailsOfPaymentsv1($item->application, $emiTranaction, $consumerDocument, $item->emi_date, $request);
                $this->getCibilReportApplication[] = $item->application->id;
            }
        }
    }

    public function checkEMIDate($application, $from, $to)
    {
        //$schedule = (new LoanManagement())->generateDues($application->id, 0, $application);
        $schedule = (new \App\Http\Controllers\Admin\EMICalculation(new Request()))->getRepaymentSchedule($application, false);
        $moratorium = Moratorium::where('application_id', $application->id)->whereNull('stopped_date')->get();
        $dates = [];
        if($moratorium) {
            foreach ($moratorium as $item) {
                $dates[] = $item->emi_date;
            }
        }

        $i = 0;
        if(isset($schedule['emis'])) {
            foreach ($schedule['emis'] as $c => $emi) {
                $emi_date = date('Y-m-d', strtotime($application->emi->emi_date . ' +' . $i . ' month'));
                unset($continue);
                while(in_array($emi_date, $dates)){
                    $emi_date = date('Y-m-d', strtotime($application->emi->emi_date . ' +' . $i . ' month'));
                    $i++;
                    $continue = 1;
                }

                if(isset($continue)){
                    $i--;
                }

                $i++;

                if (strtotime($emi_date) <= strtotime($to)) {
                    return $emi_date;
                }
            }
        }
        return false;
    }

    public function getDetailsOfPaymentsv1($application, $emiTranaction, ConsumerDocument $consumerDocument, $emi_date, Request $request)
    {
        $payments = [];
        $balanceEMI = 0;
        if($emiTranaction[$application->id]['payment']){

            $multiStageDisbursement = new MultiStageDisbursement();
            if (isset($application->emi->offer->id) && $multiStageDisbursement->canPartialDisbursement($application->emi->offer->id, $application)) {
                $offer = DisbursementOffers::where('offer_id', $application->emi->offer->id)->where('application_id', $application->id);
                $offer_count = $offer->count();
                $offer_detail = $offer->first(['per_disbursement_amount']);
                $disbursementLog = DisbursementLogs::where('application_id', $application->id)->count();
            }
            foreach ($emiTranaction[$application->id]['payment'] as $emipayment) {
                $amount_received = $emipayment->total_payable - $emipayment->amount_due;
                $emi_amount = $emipayment->emi_amount;
                if(isset($offer_detail) && $offer_detail->per_disbursement_amount &&
                    isset($offer_count) && isset($disbursementLog) && $offer_count < $disbursementLog
                ){
                    $emi_amount = $emi_amount * $offer_detail->per_disbursement_amount/100;
                }
                if ($emi_amount >= $amount_received) {
                    $balanceEMI = $balanceEMI + ($emi_amount - $amount_received);
                }
                if ($emipayment->emi_date == $emi_date) {
                    foreach ($emipayment->transaction as $transactions) {
                        $payments[] = strtotime($transactions->payment_date);
                    }
                }
            }

        }

        $member = $this->getCibilMember($application->lender_id, $request);

        $loop = 1;
        if ($application->co_applicant_name) {
            $loop++;
        }
        for ($i = 1; $i <= $loop; $i++) {
            $this->getPaymentRow($application, $member, $balanceEMI, $payments, $consumerDocument, $emiTranaction, $emi_date, $i, $request);
        }
    }

    public function getDetailsOfPayments($application, $emiTranaction, ConsumerDocument $consumerDocument, $emi_date, Request $request)
    {
        $payments = [];
        $balanceEMI = 0;
        $last_emi_date = $emi_date;
        if (isset($emiTranaction[$application->id]) && isset($emiTranaction[$application->id]['payment'])) {
            $balanceEMI = $this->getBalanceAmount($emiTranaction[$application->id], $emi_date);
            if (isset($emiTranaction[$application->id]['payment'])) {
                $position = array_search($emi_date, array_keys($emiTranaction[$application->id]['payment']));
                $last_emi_date = isset($emiTranaction[$application->id]['payment']) ? $emiTranaction[$application->id]['payment'] : [];
                if ($last_emi_date) {
                    $keys = array_keys($last_emi_date);
                    $last_emi_date = isset($keys[$position]) ? $keys[$position] : $emi_date;
                }
            }
            if (isset($emiTranaction[$application->id]['payment'][$last_emi_date]) && isset($emiTranaction[$application->id]['payment'][$last_emi_date]['payment_history']) && isset($emiTranaction[$application->id]['payment'][$last_emi_date]['payment_history']->transaction)) {
                foreach ($emiTranaction[$application->id]['payment'][$last_emi_date]['payment_history']->transaction as $transaction) {
//                    if($to != "" ) {
//                        if (strtotime($to) >= strtotime($transaction->payment_date)) {
//                            $payments[] = strtotime($transaction->payment_date);
//                        }
//                    }else{
                    //$payments[] = strtotime($transaction->payment_date);
                    //}
                }
            }
        }

        $member = $this->getCibilMember($application->lender_id, $request);

        $loop = 1;
        if ($application->co_applicant_name) {
            $loop++;
        }
        for ($i = 1; $i <= $loop; $i++) {
            $this->getPaymentRow($application, $member, $balanceEMI, $payments, $consumerDocument, $emiTranaction, $emi_date, $i, $request);
        }
    }

    public function getPaymentRow($application, $member, $balanceEMI, $payments, ConsumerDocument $consumerDocument, $emiTranaction, $emi_date, $type, Request $request)
    {
        $address = $this->getAddress($application, $type);
        $stateCode = StateModel::where('name', $address['state'])->first(['code_number']);
        $delay_days = 0;
        $overDueAmount = 0;
        if(in_array($application->state, ['closed', 'cancelled', 'cancellation in-process'])){
            $delay_days = 0;
            $overDueAmount = 0;
            $balanceEMI = 0;
        }else{
            if($emiTranaction[$application->id]){
                foreach ($emiTranaction[$application->id]['payment'] as $emis){
                    $emi_month = Carbon::parse($emis->emi_date);
                    $curr_month = Carbon::now();
                    if($emi_month <= $curr_month && $emis->payment_status != 'success'){
                        $overDueAmount += $emis->amount_due;
                        $dateDiff = $curr_month->diffInDays($emi_month);
                        if($dateDiff > $delay_days){
                            $delay_days = $dateDiff;
                        }
                    }
                }
            }
        }

        $_from = Carbon::createFromFormat('Y-m-d', $request->get('from_date'))->startOfDay()->timestamp;
        $to = Carbon::createFromFormat('Y-m-d', $request->get('to_date'))->startOfDay()->timestamp;

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

        if(!$application->emi){
            $emi = ApplicationEMICalculation::where('application_id', $application->id)->first(['emi','remaining_emi']);
        }

        if(!$application->proFormaInvoice){
            $proFormaInvoice = ProFormaInvoice::where('application_id', $application->id)->first(['loan_application_no']);
        }

        $repaymentTenure = $application->emi ? $application->emi->remaining_emi : (isset($emi) ? $emi->remaining_emi : '');
        $downPayment = 0;
        if($application->merchant && $application->merchant->charge_subvention_remaining_amount){
            $downPayment = $application->emi->upfront_from_customer;
        }

        $accountTypeCode = '05';
        $loanHypothecation = LoanHypothecationModel::where('application_id', $application->id)->whereNull('deleted_at')->exists();
        if($loanHypothecation && $application->purpose == 24){
            $accountTypeCode = '00';
            if($application->application_element->type_of_customer_application == 'Non-individual' && !in_array($application->application_element->type_of_customer, [1, 4])) {
                $accountTypeCode = '54';
            }
        }


        if(($type == 1 && !in_array($application->pan_card, $this->paymentData)) || ($type != 1 && !in_array($application->co_applicant_pan_card, $this->paymentData))){
            $this->paymentData[] = [
                'name' => ($type == 1) ? $application->name : $application->co_applicant_name,
                'dob' => ($type == 1) ? date('dmY', strtotime($application->dob)) : date('dmY', strtotime($application->co_applicant_dob)),
                'gender' => ($type == 1) ? (($application->gender == 'MALE') ? 2 : 1) : (($application->co_applicant_gender == 'MALE') ? 2 : 1),
                'pan' => ($type == 1) ? $application->pan_card : $application->co_applicant_pan_card,
                'passport' => '',
                'passport_issue_date' => '',
                'passport_expiry_date' => '',
                'voter_id' => '',
                'driving_license_number' => '',
                'driving_license_issue_date' => '',
                'driving_license_expiry_date' => '',
                'ration_car_number' => '',
                'universal_id_number' => ($type == 1) ? (strlen($application->aadhaar_card) == 12 ? $application->aadhaar_card : '') : (strlen($application->co_applicant_aadhaar_card) == 12 ? $application->co_applicant_aadhaar_card : ''),
                'additional_id_1' => '',
                'additional_id_2' => '',
                'telephone_no_mobile' => ($type == 1) ? $application->mobile_number : $application->co_applicant_mobile_number,
                'telephone_no_residence' => '',
                'telephone_no_office' => '',
                'extension_office' => '',
                'telephone_no_other' => '',
                'extension_other' => '',
                'email_1' => ($type == 1) ? $application->email : $application->co_applicant_email,
                'email_2' => '',
                'address_1' => $address['address'],
                'state_1' => $stateCode->code_number ?? '',
                'pincode_1' => $address['pincode'],
                'address_category_1' => $address['category'],
                'residence_code_1' => '',
                'address_2' => '',
                'state_2' => '',
                'pincode_2' => '',
                'address_category_2' => '',
                'residence_code_2' => '',
                'current_new_member_code' => $member['code'],
                'current_new_member_short_name' => $member['name'],
                'curr_new_account_no' => isset($application->proFormaInvoice) ? $application->proFormaInvoice->loan_application_no : (isset($proFormaInvoice) ? $proFormaInvoice->loan_application_no : ''),
                'account_type' => $accountTypeCode,
                'ownership_indicator' => ($application->co_applicant_name) ? 4 : 1, // TODO: multiple applicants/housing soc/pvt ltd etc.
                'date_opened_disbursed' => date('dmY', strtotime($consumerDocument->getDisbursedDate($application->id))),
                'date_of_last_payment' => date('dmY', strtotime($consumerDocument->getLastPaymentDate($application->id))),/*isset($emiTranaction[$application->id]) && isset($emiTranaction[$application->id][$emi_date]['amount_received']) ? $emiTranaction[$application->id][$emi_date]['amount_received'] : 0*/
                'date_closed' => ($application->state == 'closed') ? date('dmY', strtotime($consumerDocument->getLoanClosedDate($application->id))) : (((empty($balanceEMI) || $balanceEMI == 0) && $payments && $overDueAmount == 0) ? date('dmY', strtotime($consumerDocument->getLastPaymentDate($application->id))) : ''),
                'date_reported' => ($request->get('bureau') == 'cibil') ? date('dmY', $to) : date('dmY', strtotime("now")), //TODO: [internal]Correct the date after clarification
                'high_credit_sanctioned_amt' => $application->approved_amount - $downPayment,
                'current_balance' => $application->state == 'closed' ? 0 : ((isset($balanceEMI) && !empty($balanceEMI)) ? $balanceEMI : 0),
                'amt_overdue' => isset($amount_over_due->amount_over_due) && $amount_over_due->amount_over_due >= 0 ? $amount_over_due->amount_over_due : ($overDueAmount ?? ($amount_over_due->amount_over_due ?? 0)),
                'no_of_days_past_due' => $delay_days > 999 ? 999 : $delay_days,
                'Old Mbr Code' => '',
                'Old Mbr Short Name' => '',
                'Old Acc No' => '',
                'Old Acc Type' => '',
                'Old Ownership Indicator' => '',
                'Suit Filed / Wilful Default' => '',
                'Credit Facility Status' => '',
                'asset_classification' => $delay_days >= 365 ? '04' : ( $delay_days > 120 ? '02' : '01'), // TODO: will need to change after April 25, after confirmation with Accounts
                'Value of Collateral' => '', // TODO: need to add info for solar cases.
                'Type of Collateral' => '', // TODO: need to add info for solar cases.
                'Credit Limit' => '',
                'Cash Limit' => '',
                'Rate of Interest' => 0,//$application->emi->interest_rate,
                'RepaymentTenure' => sprintf("%02d", $repaymentTenure),
                'emi_amount' => $application->emi ? $application->emi->emi : (isset($emi) ? $emi->emi : ''),
                'Written- off Amount (Total)' => '',
                'Written- off Principal Amount' => '',
                'Settlement Amt' => '',
                'Payment Frequency' => '03',
                'Actual Payment Amt' => '',
                'Occupation Code' => '',
                'Income' => ($type == 1) ? $application->monthly_income : $application->co_applicant_monthly_income,
                'Net/Gross Income Indicator' => '',
                'Monthly/Annual Income Indicator' => ''
            ];
        }
    }

    public function getCibilMember($id, Request $request)
    {
        if ($id == 1) {//pride
            if ($request->get('bureau') == 'cibil') {
                return [
                    'code' => 'NB45420001',
                    'name' => 'PRIDEFIN',
                ];
            } else {
                return [
                    'code' => '027FP18918',
                    'name' => 'MKHO',
                ];
            }
        } else {
            if ($request->get('bureau') == 'cibil') {
                return [
                    'code' => 'NB49040001',
                    'name' => 'KMGLOBAL',
                ];
            } else {
                return [
                    'code' => '027FP19233',
                    'name' => 'COSR',
                ];
            }
        }
    }

    public function getBalanceAmount($application, $emiDate)
    {

        $balance_emi = 0;
        $total_emi = 0;
        $amount_received = 0;
        foreach ($application['payment'] as $key2 => $payment) {
            $bounce_charges = isset($payment['bounce_charges']) ? $payment['bounce_charges'] : 0;
            $delay_penalty = isset($payment['delay_penalty']) ? $payment['delay_penalty'] : 0;
            $charges_waived = isset($payment['charges_waived']) ? $payment['charges_waived'] : 0;
            $total_emi = $total_emi + (($payment['emi_amount'] + $bounce_charges + $delay_penalty) - $charges_waived);
            if (strtotime($key2) <= strtotime($emiDate)) {
                $amount_received = $amount_received + $payment['amount_received'];
            }
        }

        if ($total_emi >= $amount_received) {
            $balance_emi = $total_emi - $amount_received;
        }

        return $balance_emi;
    }

    public function getDelayedPaymentTransaction($from, $to, LoanManagement $emiPayment, ConsumerDocument $consumerDocument, $lender_id, Request $request)
    {

        if ($lender_id == 0) {
            $lender_id = [1, 2];
        } else {
            $lender_id = [$lender_id];
        }
        $data = EmiPayment::with(['application' => function ($query) use ($lender_id) {
            $query->whereIn('lender_id', $lender_id)->whereNotIn('merchant_id', [6478,7516,9421])/*->where('merchant_id', 4696)*/->whereNull('is_deleted');
        }])
            ->where('emi_date', '<', $from)
            ->where('payment_date', '>=', $from)->where('payment_date', '<=', $to)
            ->where('payment_status', 'success')
            ->get();
        foreach ($data as $item) {
            if (isset($item->application) && isset($item->application->id) && !in_array($item->application->id, $this->getCibilReportApplication)) {
                $this->getCibilReportApplication[] = $item->application->id;
                $emiTranaction = $emiPayment->getPaymentDueHistory($item->application_id);
                $this->getDetailsOfPaymentsv1($item->application, $emiTranaction, $consumerDocument, $item->emi_date, $request);
            }
        }

    }

    public function getAddress($application, $type)
    {
        if ($type == 1) {
            if (empty($application->permanent_address_line_1)) {
                return [
                    'address' => $application->current_address_line_1 . ', ' . $application->current_address_landmark,
                    'state' => $application->current_address_state,
                    'city' => $application->current_address_city,
                    'pincode' => $application->current_address_pincode,
                    'category' => '02'
                ];
            } else {
                return ['address' => $application->permanent_address_line_1 . ', ' . $application->permanent_address_landmark,
                    'state' => $application->permanent_address_state,
                    'city' => $application->permanent_address_city,
                    'pincode' => $application->permanent_address_pincode,
                    'category' => '01'
                ];
            }
        } else {
            return ['address' => $application->co_applicant_address_line_1 . ', ' . $application->co_applicant_address_landmark,
                'state' => $application->co_applicant_address_state,
                'city' => $application->co_applicant_address_city,
                'pincode' => $application->co_applicant_address_pincode,
                'category' => '01'
            ];
        }
    }

    public function getAddressByType($application){

        return [
            'applicant' => [
                'current' => ['address' => $application->current_address_line_1.' '.$application->current_address_landmark.', '.$application->current_address_city.' '.$application->current_address_state.' '.$application->current_address_pincode, 'pincode' => $application->current_address_pincode],
                'permanent' => ['address' => $application->permanent_address_line_1.' '.$application->permanent_address_landmark.', '.$application->permanent_address_city.' '.$application->permanent_address_state.' '.$application->permanent_address_pincode, 'pincode' => $application->permanent_address_pincode],
                'work' => ['address' => $application->work_address_line_1.' '.$application->work_address_landmark.', '.$application->work_address_city.' '.$application->work_address_state.' '.$application->work_address_pincode, 'pincode' => $application->work_address_pincode],
                'installation'=>['address' => $application->application_element->installation_address_line_1.' '.$application->application_element->installation_address_landmark .', '.$application->application_element->installation_address_city.' '.$application->application_element->installation_address_state.' '.$application->application_element->installation_address_pincode, 'pincode' => $application->application_element->installation_address_pincode]
            ],
            'co_applicant' => [
                'current' => ['address' => ($application->co_applicant_address_line_1) ? $application->co_applicant_address_line_1.' '.$application->co_applicant_address_landmark.', '.$application->co_applicant_address_city.' '.$application->co_applicant_address_state.' '.$application->co_applicant_address_pincode : '', 'pincode' => ($application->co_applicant_address_line_1) ? $application->co_applicant_address_pincode : '']
            ]
        ];
    }

    public function getCustomerCommunications($application_id)
    {
        $notifications = FCMResponse::with('user')->where('id_type', 'application_id')->where('_id', $application_id)->get();
        $sms_logs = SMSLogs::with('user')->where('_id', $application_id)->where('id_type', 'application_id')->get();

        $data = [];
        foreach ($notifications as $notification) {
            $data[] = array(
                'purpose' => ucwords(str_replace('_', ' ', $notification->notification_type)),
                'time' => $notification->created_at,
                'by' => isset($notification->user->name) ? $notification->user->name : 'unknown',
                'type' => 'FCM Notifications',
                'sent' => '-',
                'read' => '-',
                'read_time' => '-'
            );
        }

        foreach ($sms_logs as $log) {
            $data[] = array(
                'purpose' => urldecode($log->message),
                'time' => $log->created_at,
                'by' => isset($log->user->name) ? $log->user->name : 'unknown',
                'type' => $log->provider == 'ses' ? 'EMAIL': 'SMS',
                'sent' => $log->provider == 'ses' ? $log->sent : '-',
                'read' => $log->provider == 'ses' ? $log->read : '-',
                'read_time' => $log->provider == 'ses' ? $log->read_time : '-'
            );
        }

        return $data;
    }

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

        $status = 'error';
        $message = "File not generated";
        try {

            $application = ConsumerApplicationFiles::find($id);
            $applicationDetails = ConsumerApplication::where('id', $application->consumer_application_id)->first(['employee_status']);
            $data['file_type'] = $application->file_type;
            $fileData = explode('/', $application->file_path);
            $this->isInternal = true;
            $id = isset($fileData[0]) ? $fileData[0] : '';
            $prefix = isset($fileData[1]) ? $fileData[1] : '';
            $key = isset($fileData[2]) ? $fileData[2] : '';
            $path = $this->viewFile($id, $prefix, $key);

            $file = new UploadedFile(
                $path,
                $data['file_type'],
                'application/pdf',
                filesize($path),
                null,
                TRUE
            );

            $data['id'] = $application->consumer_application_id;
            $data['consumer_application_file_id'] = $id;
            $data['bank_name'] = $request->has('bank_name') ? $request->get('bank_name') : $application->bank_name;
            $data['password'] = $request->has('password') ? $request->get('password') : $application->password;
            $data['accounttype'] = $request->has('accounttype') ? $request->get('accounttype') : $application->accounttype;
            $data['statementtype'] = $request->has('statementtype') ? $request->get('statementtype') : $application->statementtype;
            $data['statemenfilettype'] = $request->has('statemenfilettype') ? $request->get('statemenfilettype') : $application->statemenfilettype;
            $data['uploaded_file'] = $file;


            if ($request->has('bank_name')) {
                $application->bank_name = $data['bank_name'];
                $application->password = $data['password'];
                $application->accounttype = $data['accounttype'];
                $application->statementtype = $data['statementtype'];
                $application->statemenfilettype = $data['statemenfilettype'];
            }


            // $finbit = (new FinBit(new Request($data)))->uploadStatement();
            $data['employmentType'] = isset($applicationDetails->employee_status) ? $applicationDetails->employee_status : '';
            $data['applicant_type'] = $application->applicant_type;
            $bankStatement = (new Pirimid(new Request($data)))->uploadBankStatement(false);
            // if (isset($finbit->accountUID)) {
            //     if (isset($finbit->accountUID[0])) {
            //         $application->accountUID = json_encode($finbit->accountUID);
            //         $application->save();
            //         $message = "File generated successfully";
            //         $status = 'success';
            //     } else {
            //         $application->accountUID = json_encode([$finbit->accountUID]);
            //         $application->save();
            //         $message = "File generated successfully";
            //         $status = 'success';
            //     }
            if (isset($bankStatement->trackingId) && isset($bankStatement->status) && $bankStatement->status == 'PENDING') {
                $message = 'Bank Statement Analysis under progress';
            } else{
                ConsumerApplicationFiles::where('id',$application->id)->update(['finbit_analysis_date' => Carbon::now()->toDateTimeString()]);
            }
        } catch (\Exception $e) {

        }

        if(isset($path) && $path && file_exists($path)){
            unlink($path);
        }

        \Session::flash($status, $message);
        $link = isset($data) ? '/admin/consumer-applications/edit/' . $data['id'] : '/admin/consumer-applications';
        return redirect()->to($link);
    }

    public function getMerchantAnalysis(Request $request)
    {
        set_time_limit(0);
        return (new TestingController())->getMerchantWiseCustomerAppData($request);
    }

    public function setUserAvailability(Request $request){
        $userAvailability = User::where('id', $request->get('user_id'))->first(['id','user_availability']);
        if (isset($userAvailability->id) && $userAvailability->user_availability != $request->get('type')){
            User::where('id', $userAvailability->id)->update(['user_availability' => $request->get('type')]);
        }

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

    public function sendInProcessWhatsAppMessage($application_id){
        $application = ConsumerApplication::with('application_element','merchant')->where('id', $application_id)->first(['mobile_number','name','id','merchant_id','co_applicant_mobile_number','co_applicant_name','updated_by']);
        $status = StatusLogs::where('application_id', $application_id)->where('status', 'in-process')->get();
        if(in_array($application->updated_by, ['Mobile App','PWA']) || ($application->application_element && $application->application_element->soft_lead)) {
            if (isset($application->id) && count($status) <= 1) {
                $user = User::where('mobile_number', $application->mobile_number)->first(['id','user_verified']);
                if (isset($user->user_verified) && !$user->user_verified) {
                    //sendWhatsAppMessage($application->mobile_number, ['id' => $application_id, 'templateId' => Templates::$stop_message_v1, 'args' => [$application->name]]);
                }
                if ($application->co_applicant_name && $application->co_applicant_mobile_number) {
                    $user = User::where('mobile_number', $application->co_applicant_mobile_number)->first(['user_verified']);
                    if (isset($user->user_verified) && !$user->user_verified) {
                        //sendWhatsAppMessage($application->co_applicant_mobile_number, ['id' => $application_id, 'templateId' => Templates::$stop_message_v1, 'args' => [$application->co_applicant_name]]);
                    }
                }
            }
        }

        if((count($status) <= 1) && ($application->updated_by != 'consumer_app')){
            $merchant_name = isset($application->merchant->merchant_name) ? $application->merchant->merchant_name : "";
            if($application->merchant_id == 7369){
                sendWhatsAppMessage($application->mobile_number, ['id' => $application_id, 'templateId' => Templates::$loanshastra_nondownload_app_v1, 'args' => [$application->name]]);
            }else if($application->merchant_id == 7865 || (isset($application->merchant->anchor_merchant_id) && $application->merchant->anchor_merchant_id == 7865)){
                sendWhatsAppMessage($application->mobile_number, ['id' => $application_id, 'templateId' => Templates::$apply_loan_application_v1, 'args' => [$application->name,$merchant_name]]);
            }else{
                sendWhatsAppMessage($application->mobile_number, ['id' => $application_id, 'templateId' => Templates::$download_consumer_app_v2, 'args' => [$application->name, 'https://bit.ly/33UhWD2']]);
            }
        }


        if ($application->merchant && $application->merchant->contact_number) {


            $user = User::where('mobile_number',$application->merchant->contact_number)->first(['id','whatsapp_api','user_verified']);
            if($user) {
                $init = $user->whatsapp_api && $user->whatsapp_api ? $user->whatsapp_api : false;
                if (!$init) {
                    $init = is_null($user->whatsapp_api) && $user->user_verified ? true : false;
                }

                if ($init && !$user->whatsapp_api) {
                    User::where('id', $user->id)->update(['whatsapp_api' => 1]);
                }

                if($init){
                    //sendWhatsAppMessage($application->merchant->contact_number, ['id' => $application->merchant->id, 'templateId' => Templates::$stop_message_merchant_v1, 'args' => [$application->merchant->merchant_name, $application->name]]);
                }
            }
        }
    }

    public function checkApprovedPinCode($id, $check = false)
    {

        try {

            $dataLists = $this->getUnapprovedPincodes($id);
            if ($dataLists['unapproved_pin_codes'] && (!isset($dataLists['approver_data_exist']->id) || $check)) {

                if ($check && isset($dataLists['approver_data_exist']->id)) {
                    $user = Auth::user();
                    ApproverData::where('id', $dataLists['approver_data_exist']->id)->update(['deleted_by' => $user ? $user->id : 0]);
                    ApproverData::where('id', $dataLists['approver_data_exist']->id)->delete();
                }

                $applicant_data = ConsumerApplication::with('advisor')->where('id', $id)->first(['id', 'created_by', 'name', 'current_address_line_1', 'current_address_state', 'current_address_city', 'current_address_pincode', 'current_address_landmark', 'permanent_address_line_1', 'permanent_address_state', 'permanent_address_city', 'permanent_address_pincode', 'permanent_address_landmark', 'work_address_line_1', 'work_address_state', 'work_address_city', 'work_address_pincode', 'work_address_landmark', 'co_applicant_address_line_1', 'co_applicant_address_state', 'co_applicant_address_city', 'co_applicant_address_pincode', 'co_applicant_address_landmark']);

                $managerLists = StatusLogs::with('user')->where('application_id', $id)->get();

                $emails = ['address_approvers@creditfair.in'];
                foreach ($managerLists as $manager) {
                    if ($manager->user && $manager->user->email && $applicant_data->created_by != $manager->user->id && $manager->user->is_manager && $manager->user->user_type >= 5 && !in_array($manager->user->email, $emails)) {
                        array_push($emails, $manager->user->email);
                    }
                }

                $body = 'Dear Manager,<br/> Please check if loan application of ' . $applicant_data->name . ' <a href="' . asset('admin/consumer-verification/' . $applicant_data->id . '/get') . '">View Application</a> is a serviceable address or if we are willing to give exception?';
                $subject = $applicant_data->name . ' case requires address pin code approval';
                $data = ['email' => $emails, 'subject' => $subject];
                if (!empty($data['email'])) {
                    \Mail::send('emails.reminders.basic_reminder',
                        ['body' => $body]
                        , function ($message) use ($data) {
                            $message->to($data['email'])->subject($data['subject']);
                            //$message->cc(_env('NOTIFY_EMAIL', ''));
                        });
                }
            }
        }catch (\Exception $e){

        }

    }

    public function pinApprovalData(Request $request)
    {

        $status = 'FAIL';
        $message = 'Something went wrong';


        try {
            $user_id = (Auth::user()) ? Auth::user()->id : 0;
            $application_id = $request->get('application_id');
            $reason = $request->get('comment');

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

            $approver_data = array('user_id' => $user_id, "application_id" => $application_id, "reason" => $reason,'created_at'=>$created_at);

            //$approverData = ApproverData::insertGetId($approver_data);
            ApproverData::insertGetId($approver_data);

            $application_id = $request->get('application_id');
            $application = ConsumerApplication::with('advisor')->where('id', $application_id)->first(['name', 'created_by','current_address_pincode', 'permanent_address_pincode', 'merchant_id']);

            if ($application->advisor) {
                $link = asset('admin/consumer-verification/' . $application_id . '/get');
                $body = 'Dear '.$application->advisor->name.'<br/>Please complete the pending process for ' . $application->name.'<a href="'.$link.'">View Application</a>';

                $subject = $application->name . " address has been approved";
                $data = ['email' => [$application->advisor->email], 'subject' => $subject];
            
                $managerLists = StatusLogs::with('user')->where('application_id', $application_id)->get();

                foreach ($managerLists as $manager) {
                    if ($manager->user && $manager->user->email && $application->created_by != $manager->user->id && $manager->user->user_type >= 5 && !in_array($manager->user->email, $data['email'])) {
                        array_push($data['email'], $manager->user->email);
                    }
                }
            }

            if (isset($data['email']) && !empty($data['email'])) {
                \Mail::send('emails.reminders.basic_reminder',
                    ['body' => $body]
                    , function ($message) use ($data) {
                        $message->to($data['email'])->subject($data['subject']);
                        // $message->cc(_env('NOTIFY_EMAIL', ''));
                    });

                $status = 'OK';
                $message = 'The pin code has been successfully approved!';
            }else{
                $status = 'OK';
                $message = 'Pincode approved but advisor email is empty!';
            }

        } catch (\Exception $e) {
            return ['status' => $status, 'message' => $message];
        }

        return ['status' => $status, 'message' => $message];

    }

    // public function exportCronData($file){
    //     $path = storage_path('app/exported/'.$file);
    //     if(file_exists($path)){
    //         return response()->download($path);
    //     }
    //     return abort(404);
    // }

    public function getUnapprovedPincodesV1($id)
    {
        if(!isset($id->id)){
            $all_pin_codes = ConsumerApplication::with('application_element')->where('id', $id)->first(['id', 'name', 'current_address_line_1', 'current_address_state', 'current_address_city', 'current_address_pincode', 'current_address_landmark', 'permanent_address_line_1', 'permanent_address_state', 'permanent_address_city', 'permanent_address_pincode', 'permanent_address_landmark', 'work_address_line_1', 'work_address_state', 'work_address_city', 'work_address_pincode', 'work_address_landmark', 'co_applicant_address_line_1', 'co_applicant_address_state', 'co_applicant_address_city', 'co_applicant_address_pincode', 'co_applicant_address_landmark']);
        }else{
            $all_pin_codes = $id;
        }


        $is_current_address_pincode = true;
        $customer_pincode = ['current_address_pincode' => $all_pin_codes->current_address_pincode, 'installation_address_pincode' => $all_pin_codes->application_element->installation_address_pincode];

        if(empty($all_pin_codes->current_address_pincode)){
            $is_current_address_pincode = false;
        }

        $approved_pin_code_list = ApprovedPincodeLists::get(['pin_codes']);
        $p = [];
        foreach ($approved_pin_code_list as $f) {
            if ($f->pin_codes) {
                $p[] = $f->pin_codes;
            }
        }

        $unapproved_pincodes = array(); //list of unapproved pin codes of user
        $approver_data_exist=ApproverData::where('application_id', $all_pin_codes->id)->first();

        foreach ($customer_pincode as $key => $value) {
            if ($value && !in_array($value, $p)) {
                if($key == 'current_address_pincode'){
                    $is_current_address_pincode = false;
                }
                array_push($unapproved_pincodes, $value);
            }
        }

        $addressees = $this->getAddressByType($all_pin_codes);
        $all_unapproved_address = array();

        // Remove 'co_applicant', 'work', and 'permanent' addresses
        unset($addressees['co_applicant']);
        unset($addressees['applicant']['work']);
        unset($addressees['applicant']['permanent']);

        foreach ($addressees as $applicant_type => $address) {
            foreach ($address as $address_type => $item) {
                if ((in_array($item['pincode'], $unapproved_pincodes) && !(empty($item['address'])))) {
                    $all_unapproved_address[] = ['address_type' => $address_type, 'address' => $item['address']];
                }
            }
        }

        return ['all_pin_codes' => $all_pin_codes, 'is_current_address_pincode' => $is_current_address_pincode, 'full_approved_address' => $all_unapproved_address, 'unapproved_pin_codes' => $unapproved_pincodes,'approver_data_exist'=>$approver_data_exist];

    }

    public function getUnapprovedPincodes($id)
    {
        if(!isset($id->id)){
            $all_pin_codes = ConsumerApplication::with('application_element')->where('id', $id)->first(['id', 'name', 'current_address_line_1', 'current_address_state', 'current_address_city', 'current_address_pincode', 'current_address_landmark', 'permanent_address_line_1', 'permanent_address_state', 'permanent_address_city', 'permanent_address_pincode', 'permanent_address_landmark', 'work_address_line_1', 'work_address_state', 'work_address_city', 'work_address_pincode', 'work_address_landmark', 'co_applicant_address_line_1', 'co_applicant_address_state', 'co_applicant_address_city', 'co_applicant_address_pincode', 'co_applicant_address_landmark']);
        }else{
            $all_pin_codes = $id;
        }


        $is_current_address_pincode = true;
        $customer_pincode = ['current_address_pincode' => $all_pin_codes->current_address_pincode, 'installation_address_pincode' => $all_pin_codes->application_element->installation_address_pincode];

        if(empty($all_pin_codes->current_address_pincode)){
            $is_current_address_pincode = false;
        }

//        $approved_pin_code_list = ApprovedPincodeLists::get(['pin_codes']);
//        $p = [];
//        foreach ($approved_pin_code_list as $f) {
//            if ($f->pin_codes) {
//                $p[] = $f->pin_codes;
//            }
//        }

        $unapproved_pincodes = array(); //list of unapproved pin codes of user
        $approver_data_exist=ApproverData::where('application_id', $all_pin_codes->id)->first(['id']);

        foreach ($customer_pincode as $key => $value) {
            //if ($value && !in_array($value, $p)) {
            if($value) {
                $aPincode = ApprovedPincodeLists::where('pin_codes', $value)->first(['id']);
                if (!isset($aPincode->id)) {
                    if ($key == 'current_address_pincode') {
                        $is_current_address_pincode = false;
                    }
                    array_push($unapproved_pincodes, $value);
                }
            }
        }

        $addressees = $this->getAddressByType($all_pin_codes);
        $all_unapproved_address = array();

        // Remove 'co_applicant', 'work', and 'permanent' addresses
        unset($addressees['co_applicant']);
        unset($addressees['applicant']['work']);
        unset($addressees['applicant']['permanent']);

        foreach ($addressees as $applicant_type => $address) {
            foreach ($address as $address_type => $item) {
                if ((in_array($item['pincode'], $unapproved_pincodes) && !(empty($item['address'])))) {
                    $all_unapproved_address[] = ['address_type' => $address_type, 'address' => $item['address']];
                }
            }
        }

        return ['all_pin_codes' => $all_pin_codes, 'is_current_address_pincode' => $is_current_address_pincode, 'full_approved_address' => $all_unapproved_address, 'unapproved_pin_codes' => $unapproved_pincodes,'approver_data_exist'=>$approver_data_exist];

    }

    public function getBlacklist(){
        return view('admin.rbiBlacklist');
    }

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

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

        }

        $file = $request->file('payment_file');
        $extension = $file->getClientOriginalExtension();
        try {
            if(strpos($extension, 'xls') !== false) {
                Excel::import(new RBIBlacklistImport(), $file);
            }else{

            }
            \Session::flash('success', 'Blacklist updated successfully');
            return redirect()->back();
        }catch (\Exception $e) {
            \Session::flash('error', 'Something went wrong, ' . $e->getFile() . $e->getLine());
            return redirect()->back();
        }

    }
    public function getBlacklistData($application)
    {
        $list = '';
        $flag= '';
        if($application->pan_card){
            $list = RBIBlacklist::where('document_value', $application->pan_card)->where('document_type','like','%pan%')->first(['id']);
            $flag = 'PAN Card of Applicant';
        }
        if(!isset($list->id) && $application->aadhaar_card){
            $list = RBIBlacklist::where('document_value', $application->aadhaar_card)->where('document_type','like','%aadhar%')->first(['id']);
            $flag= 'Adhaar Card of Applicant';

        }
        if(!isset($list->id) && $application->co_applicant_pan_card){
            $list = RBIBlacklist::where('document_value', $application->co_applicant_pan_card)->where('document_type','like','%pan%')->first(['id']);
            $flag='PAN Card of Co-applicant';

        }
        if(!isset($list->id) && $application->co_applicant_aadhaar_card){
            $list = RBIBlacklist::where('document_value', $application->co_applicant_aadhaar_card)->where('document_type','like','%aadhar%')->first(['id']);
            $flag='Adhaar Card of Co-applicant';

        }

        return !isset($list->id) ? ['status' => false] : ['status' => true, 'flag' => $flag];
    }

    public function generateTelecomOTP(Request $request){
        $telecom = new TelecomDetails();
        $response = $telecom->generateOtp($request->get('mobile_number'));

        if($response == false){
            return \response()->json(['status' => 'FAIL','message' => 'Can\'t generate Telecom Data']);
        }else {
            $this->senTelecomOTPCommunication($request, $response['request_id']);
            return \response()->json(['status' => 'OK','request_id' => $response['request_id']]);
        }
    }

    public function senTelecomOTPCommunication(Request $request, $request_id){
        $hashids = new Hashids('Creditfair by CS', 20);
        $hashed_id = $hashids->encode($request->get('application_id'));
        $application = ConsumerApplication::where('id', $request->get('application_id'))->first(['id','name']);
        $url = Shortio::getUrl(asset('otp-verification/'.$hashed_id.'/'.$request_id));
        $message = "Dear ".$application->name.",<br/>Please enter the OTP to verify your phone number by clicking here - ".$url." <br/>By sharing OTP you agree to Credit Fair's terms and conditions https://bit.ly/2QRVgjd for the loan application and have no objection to them conducting a credit check or being contacted by them. Download the consumer application to track your application https://bit.ly/3pkSXS6<br/>Thanks,<br/>Team Credit Fair";

        $entity = ['templateid' => '1307162710700399645', 'entityid' => Templates::$entityid];
        send_sms($request->get('mobile_number'), ['message'=>$message,'id'=>$application->id,'id_type'=>'application_id','templateId' => Templates::$telecom_otp, 'args' => [$application->name, $url], 'templateDetails' => $entity]);
    }

    public function verifyTelecomOTP(Request $request){
        $telecom = new TelecomDetails();
        $response = $telecom->verifyOtp($request->get('request_id'), $request->get('otp'), $request->get('id'), $request->get('mobile_number'));
        if($response == false){
            return \response()->json(['status' => 'FAIL','message' => 'Can\'t verify OTP']);
        }else {
            return \response()->json(['status' => 'OK','message' => 'OTP verified successfully']);
        }
    }

    public function getCoronaHotspot(){
        return view('admin.corona_hotspot');
    }

    public function importCoronaHotspot(Request $request){
        if ($request->has('corona_file')) {

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

        }
        $file = $request->file('corona_file');
        $extension = $file->getClientOriginalExtension();
        try {
            if(strpos($extension, 'xls') !== false) {
                Excel::import(new Corona(), $file);
            }else{

            }
            \Session::flash('success', 'Hotspot Data uploaded successfully');
            return redirect()->back();
        }catch (\Exception $e) {
            \Session::flash('error', 'Something went wrong, ' . $e->getFile() . $e->getLine());
            return redirect()->back();
        }

    }

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

        $consumer_application = ConsumerApplication::where('id', $id)->first(['id', 'state']);
        $message = '';
        $name = '';
        $status_changed_by = '';

        if($consumer_application->state == 'rejected' || $consumer_application->state == 'approved' || $consumer_application->state == 'waiting for documents'){
            $existing_request = Comments::where('application_id', $id)->where('request_review', 0)->first();

            if(!$existing_request) {

                $requested_by = User::where('id', $request->get('requested_by'))->first(['name']);
                $application_link = asset("admin/consumer-applications/edit/" . $id);

                $comment = new Comments();
                $comment->application_id = $id;
                $comment->user_id = $request->get('requested_by');
                $comment->comment = $request->get('request_reason');
                $comment->request_review = ($request->has('request_flag') && $request->get('request_flag')) ? 1 : 0;
                $comment->save();

                if($consumer_application->state == 'rejected'){
                    $status_changed_by = StatusLogs::where('application_id', $id)->where('status', 'rejected')->first(['user_id']);
                    $rejected_by = User::where('id', $status_changed_by->user_id)->first(['name']);
                    $message = $requested_by->name." has requested review of case rejected by ".$rejected_by->name.". \nReason for request:".$request->get('request_reason');

                }
                else if($consumer_application->state == 'waiting for documents') {
                    $status_changed_by = StatusLogs::where('application_id', $id)->where('status', 'waiting for documents')->first(['user_id']);
                    $waiting_documents_by = User::where('id', $status_changed_by->user_id)->first(['name']);
                    $message = $requested_by->name." has requested review of case a status changed from waiting for decision to waiting for documents by ".$waiting_documents_by->name.". \nReason for request:".$request->get('request_reason');
                }
                else{
                    $status_changed_by = StatusLogs::where('application_id', $id)->where('status', 'approved')->first(['user_id']);
                    $approved_by = User::where('id', $status_changed_by->user_id)->first(['name']);
                    $message = $requested_by->name." has requested review of case approved by ".$approved_by->name.". \nReason for request:".$request->get('request_reason');
                }


                (new Slack(new Request(['title' => 'Case Review Request', 'fields' => ['Message' => $message, 'application_id' => $id, 'link' => $application_link], 'group' => Slack::$CASE_REVIEWS])))->send();

                return \response(['status' => 'OK', 'message' => 'Request Sent Successfully!']);

            }else{

                return \response(['status'=>'FAIL', 'message'=> 'Request has already been sent!']);
            }
        }
    }

    public function submitCaseReviewRequest(Request $request, $id)
    {
        $consumer_application = ConsumerApplication::where('id', $id)->first(['id', 'state']);

        if (!$consumer_application) {
            return \response(['status' => 'FAIL', 'message' => 'Application not found.'], 404);
        }

        if (strtolower($consumer_application->state) !== 'disbursement query') {
            return \response(['status' => 'FAIL', 'message' => 'Case review can be requested only when state is Disbursement Query.'], 422);
        }

        $reasons = $request->get('reasons', []);
        if (!is_array($reasons)) {
            $reasons = [$reasons];
        }
        $reasons = array_values(array_filter(array_map(function ($r) {
            return is_string($r) ? trim($r) : '';
        }, $reasons), function ($r) {
            return $r !== '';
        }));

        if (count($reasons) === 0) {
            return \response(['status' => 'FAIL', 'message' => 'Please enter at least one review reason.'], 422);
        }

        $appId = $consumer_application->id;
        $userId = Auth::user()->id;
        $requestTime = Carbon::now();

        $rows = [];
        foreach ($reasons as $reason) {
            $rows[] = [
                'app_id' => $appId,
                'request_message' => $reason,
                'request_by' => $userId,
                'request_time' => $requestTime,
                'status' => 'PENDING',
            ];
        }

        CaseReviewRequest::insert($rows);

        $disbursementQueryLog = StatusLogs::where('application_id', $consumer_application->id)
            ->where('status', 'disbursement query')
            ->orderBy('created_at', 'desc')
            ->first(['user_id']);
        $assignedUser = $disbursementQueryLog && $disbursementQueryLog->user_id
            ? User::where('id', $disbursementQueryLog->user_id)->first(['name'])
            : null;
        $mention = $assignedUser && $assignedUser->name ? '@' . $assignedUser->name : '@user';

        $queryListLines = [];
        foreach ($reasons as $idx => $reason) {
            $queryListLines[] = ($idx + 1) . '. ' . $reason;
        }
        $headerNoun = count($reasons) === 1 ? 'query' : 'queries';
        $comment = new Comments();
        $comment->application_id = $consumer_application->id;
        $comment->user_id = $userId;
        $comment->comment = $mention . ' please review the application with the following ' . $headerNoun . ' raised:<br>' . implode('<br>', $queryListLines);
        $comment->save();

        $assignedUserId = $disbursementQueryLog && $disbursementQueryLog->user_id ? $disbursementQueryLog->user_id : null;
        $application_link = asset("admin/consumer-applications/edit/" . $consumer_application->id);
        
        $titleHtml = $mention . " Case Review Request Raised</b><br><br>" . implode("<br>", $queryListLines) . "<br><br><b>App ID Link:</b> " . $consumer_application->id . " | <a href='" . $application_link . "'>link</a><b>";
        
        $requestData = [
            'title' => $titleHtml,
            'fields' => [],
            'group' => Slack::$DISBURSEMENT_QUERY,
            'hide_footer' => true
        ];
        
        if ($assignedUserId) {
            $requestData['tagging'] = [$assignedUserId];
        }

        (new Slack(new Request($requestData)))->send();

        return \response(['status' => 'OK', 'message' => 'Case Review Request Submitted Successfully']);
    }

    public function listCaseReviewRequests($id)
    {
        if (!Session::has('Reply_for_Case_Review|-80')) {
            return \response(['status' => 'FAIL', 'message' => 'You do not have permission to access this section.'], 403);
        }
        $consumer_application = ConsumerApplication::where('id', $id)->first(['id']);
        if (!$consumer_application) {
            return \response(['status' => 'FAIL', 'message' => 'Application not found.'], 404);
        }

        $rows = CaseReviewRequest::with(['requester:id,name', 'responder:id,name'])
            ->where('app_id', $consumer_application->id)
            ->orderByRaw("CASE WHEN status = 'PENDING' THEN 0 ELSE 1 END")
            ->orderBy('id', 'asc')
            ->get();

        $formatted = $rows->map(function ($r) {
            return [
                'id' => (int) $r->id,
                'request_message' => $r->request_message,
                'request_time' => $r->request_time ? Carbon::parse($r->request_time)->format('d M, Y H:i') : '',
                'requested_by_name' => optional($r->requester)->name ?: 'Unknown',
                'response_message' => $r->response_message,
                'response_time' => $r->response_time ? Carbon::parse($r->response_time)->format('d M, Y H:i') : '',
                'responded_by_name' => optional($r->responder)->name,
                'status' => $r->status,
            ];
        })->all();

        return \response(['status' => 'OK', 'data' => $formatted]);
    }

    public function respondCaseReviewRequest(Request $request, $requestId)
    {
        if (!Session::has('Reply_for_Case_Review|-80')) {
            return \response(['status' => 'FAIL', 'message' => 'You do not have permission to perform this action.'], 403);
        }
        $action = strtoupper(trim((string) $request->get('action')));
        if (!in_array($action, ['APPROVED', 'REJECTED'], true)) {
            return \response(['status' => 'FAIL', 'message' => 'Invalid action.'], 422);
        }

        $responseMessage = trim((string) $request->get('response_message'));
        if ($responseMessage === '') {
            return \response(['status' => 'FAIL', 'message' => 'Response reason is mandatory.'], 422);
        }

        $entry = CaseReviewRequest::where('id', $requestId)->first();
        if (!$entry) {
            return \response(['status' => 'FAIL', 'message' => 'Request not found.'], 404);
        }

        if (strtoupper((string) $entry->status) !== 'PENDING') {
            return \response(['status' => 'FAIL', 'message' => 'This request has already been responded to.'], 422);
        }

        $entry->response_message = $responseMessage;
        $entry->response_by = Auth::user()->id;
        $entry->response_time = Carbon::now();
        $entry->status = $action;
        $entry->save();

        return \response([
            'status' => 'OK',
            'message' => $action === 'APPROVED' ? 'Request approved.' : 'Request rejected.',
            'data' => [
                'id' => (int) $entry->id,
                'status' => $entry->status,
                'response_message' => $entry->response_message,
                'response_time' => Carbon::parse($entry->response_time)->format('d M, Y H:i'),
                'responded_by_name' => Auth::user()->name,
            ],
        ]);
    }

    public function updateAppDataInfo(Request $request){
        if($request->has('user_id')){
            $application = ConsumerApplication::where('user_id', $request->get('user_id'))->where('merchant_id','!=', 21)->whereNull('is_deleted')->orderBy('created_at','desc')->first(['id','merchant_id','name']);
            if(isset($application->id)){
                $merchant = Merchant::where('id', $application->merchant_id)->where('is_guest_active',1)->first(['id','merchant_name as name']);
                if(isset($merchant->id)) {
                    $mobileData = $this->getUserFormattedData($request->get('user_id'), true);
                    if ($mobileData['charges']) {
                        $link = asset("admin/consumer-application/get-score-card/".$application->id);
                        //$group = $request->has('status') ? 'payment_collection' : Slack::$CREDIT_DECISION;
                        (new Slack(new Request(['title' => 'Check the Bounce/Charges SMS received by '.$application->name, 'fields' => ['Merchant Name' => $merchant->name, 'application_id' => $application->id, 'score card' => $link], 'group' => Slack::$permissions_data_alerts])))->send();
                    }
                }
            }
        }
    }

    public function saveAutoAbortComment($application_id){

        Comments::insert([
            'application_id' => $application_id,
            'user_id' => 0,
            'comment' => 'This case was auto-aborted because we haven\'t heard from the customer.',
            'show_consumer' => 0,
            'show_merchant' => 0,
            'created_at' => Carbon::now()->toDateTimeString(),
            'updated_at' => Carbon::now()->toDateTimeString(),
            'type' => 'consumer'

        ]);
    }

    public function mapStates(Request $request)
    {
        $error_flag = 0;
        if($request->get('keyup') == 1){

            $state_data = Pincode::where('pincode', Input::get('pincode'))->first(['state']);

            if (isset($state_data->state) && !empty($state_data->state)) {

                return \response(['status' => 'OK', 'keyup' => 1, 'state_name' => $state_data->state]);

            }else{
                \response(['status' => 'FAIL', 'keyup'=> null, 'state_name' =>'' ]);

            }

        }else{
            //filled pincodes
            $current_address_pin = $request->has('current_pin') && !empty($request->get('current_pin')) ? $request->get('current_pin') : '';
            $permanent_address_pin = $request->has('permanent_pin') && !empty($request->get('permanent_pin')) ? $request->get('permanent_pin') : '';

            $co_applicant_address_pin = $request->has('co_applicant_pin') && !empty($request->get('co_applicant_pin')) ? $request->get('co_applicant_pin') : '';


            //filled states
            $current_filled_state = $request->has('current_state') && !empty($request->get('current_state')) ? $request->get('current_state') : '';

            $permanent_filled_state = $request->has('permanent_state') && !empty($request->get('permanent_state')) ? $request->get('permanent_state') : '';

            $co_applicant_filled_state = $request->has('co_applicant_state') && !empty($request->get('co_applicant_state')) ? $request->get('co_applicant_state') : '';

            $current_address = Pincode::where('pincode', $current_address_pin)->first(['state']);
            $permanent_address = Pincode::where('pincode', $permanent_address_pin)->first(['state']);
            $co_applicant_address = Pincode::where('pincode', $co_applicant_address_pin)->first(['state']);
            $mapped_states = [$current_address, $permanent_address, $co_applicant_address];
            $filled_states = [$current_filled_state, $permanent_filled_state, $co_applicant_filled_state];
            $i = -1;

            foreach($mapped_states as $state){
                $i++;
                if(isset($state->state) && !empty($state->state)){
                    $state_name = ucwords(strtolower($state->state));
                    if (isset($filled_states[$i]) && !empty($filled_states[$i]) )  {
                        if ($state_name != $filled_states[$i]) {
                            $error_flag = 1;
                            break;

                        };

                    }
                }

            }

            if($error_flag == 0){

                return \response(['status' => 'OK', 'keyup' => 2]);

            }else{

                return \response(['status' => 'FAIL', 'keyup' => 0 ]);

            }

        }
    }

    public function sendMessageOnWhatsApp($id, $type, $otp = false){

        try {
            $data = $id;
            $id = isset($data->id) ? $data->id : $id;
            $serviceType = '';
            $application = is_array($id) ? $id : ConsumerApplication::with('merchant')->find($id);
            if(BNPL::is($application->merchant_id)){
                return true;
            }
            if (!$otp || $otp != 'single') {
                switch ($type) {
                    case 'admin':
                        $templateId = $application->co_applicant_name && $application->co_applicant_mobile_number ? Templates::$admin_app_received_2_v2 : Templates::$admin_app_received_1_v2;
                        if (!empty($application->lender_id) && $application->lender_id === ConsumerApplication::AVANSE_LENDER_ID) {
                            $templateId =  Templates::$customer_app_received_avanse;
                        }
                        $args = $application->co_applicant_name && $application->co_applicant_mobile_number ? [$application->name, $application->co_applicant_name, $application->merchant->merchant_name] : [$application->name, $application->merchant->merchant_name, "9967235047"];
                        sendWhatsAppMessage($application->mobile_number, ['id' => $id, 'templateId' => $templateId, 'args' => $args], $serviceType);
                        if($application->co_applicant_name && $application->co_applicant_mobile_number){
                            sendWhatsAppMessage($application->co_applicant_mobile_number, ['id' => $id, 'templateId' => $templateId, 'args' => $args], $serviceType);
                        }
                        User::where('mobile_number', $application->mobile_number)->update(['whatsapp_api' => 1]);
                        User::where('mobile_number', $application->co_applicant_mobile_number)->update(['whatsapp_api' => 1]);
                        break;
                    case 'website':
                        $tmpl =  Templates::$website_app_received_v1;
                        if (!empty($application->lender_id) && $application->lender_id === ConsumerApplication::AVANSE_LENDER_ID) {
                            $tmpl =  Templates::$customer_app_received_avanse;
                        }
                        sendWhatsAppMessage($application->mobile_number, ['id' => $id, 'templateId' => $tmpl, 'args' => ["https://bit.ly/2QRVgjd"]], $serviceType);
                        if($application->co_applicant_name && $application->co_applicant_mobile_number){
                            sendWhatsAppMessage($application->co_applicant_mobile_number, ['id' => $id, 'templateId' => $tmpl, 'args' => ["https://bit.ly/2QRVgjd"]], $serviceType);
                        }
                        break;
                    case 'customer':
                    case 'project_lead':
                        $tmpl =  Templates::$customer_app_received_v2;
                        if (!empty($application->lender_id) && $application->lender_id === ConsumerApplication::AVANSE_LENDER_ID) {
                            $tmpl =  Templates::$customer_app_received_avanse;
                        }
                        sendWhatsAppMessage($application->mobile_number, ['id' => $id, 'templateId' => $tmpl, 'args' => [$application->name , '9967235047']], $serviceType);
                        if($application->co_applicant_name && $application->co_applicant_mobile_number){
                            sendWhatsAppMessage($application->co_applicant_mobile_number, ['id' => $id,
                                'templateId' => $tmpl, 'args' => [$application->co_applicant_name, '9967235047']], $serviceType);
                        }
                        if($type == 'project_lead'){
                            User::where('mobile_number', $application->mobile_number)->update(['whatsapp_api' => 1]);
                        }
                        break;
                    case 'merchant':
                        $tmpl =  Templates::$merchant_app_received_v2;
                        if (!empty($application->lender_id) && $application->lender_id === ConsumerApplication::AVANSE_LENDER_ID) {
                            $tmpl =  Templates::$customer_app_received_avanse;
                        }
                        sendWhatsAppMessage($application->mobile_number, ['id' => $id, 'templateId' => $tmpl, 'args' => [$application->name, $application->merchant->merchant_name,'9967235047']], $serviceType);
                        if($application->co_applicant_name && $application->co_applicant_mobile_number){
                            sendWhatsAppMessage($application->co_applicant_mobile_number, ['id' => $id, 'templateId' => $tmpl, 'args' => [$application->co_applicant_name, $application->merchant->merchant_name,'9967235047']], $serviceType);
                        }
                        break;
                }
            }

            if ($otp || in_array($type, ['admin', 'customer'])) {
                //sendWhatsAppMessage($application->mobile_number, ['id' => $id, 'templateId' => Templates::$stop_message_v1, 'args' => [$application->name]], $serviceType);
                if($application->co_applicant_name && $application->co_applicant_mobile_number){
                    //sendWhatsAppMessage($application->co_applicant_mobile_number, ['id' => $id, 'templateId' => Templates::$stop_message_v1, 'args' => [$application->co_applicant_name]], $serviceType);
                }
            }
        }catch (\Exception $e){
            (new Slack(new Request(['title'=>'Message Error (Testing)','fields'=>['Application ID'=>$id,'error'=>$e->getMessage(),'line'=>$e->getLine(),'trace'=>$e->getTraceAsString(),'application_id'=>$id,'id_type'=>'application_id']])))->send();
        }
    }

    public function getRefferenceValidation($consumer_applications)
    {


        if (isset($consumer_applications->documents) && !empty($consumer_applications->documents)) {
            foreach($consumer_applications->documents as $document){
                if($document->file_type == 'reference'){
                    return true;
                }
            }

        }

        if (isset($consumer_applications->application_element) && !empty($consumer_applications->application_element)) {
            if (isset($consumer_applications->application_element->reference_contact_1) && !empty($consumer_applications->application_element->reference_contact_1) && isset($consumer_applications->application_element->reference_contact_2) && !empty($consumer_applications->application_element->reference_contact_2)) {

                $reference1 = $consumer_applications->application_element->reference_contact_1;
                $reference2 = $consumer_applications->application_element->reference_contact_2;

                $reference_1_called = CallLogs::where('_id', $consumer_applications->id)->where('id_type','application_id')->where('status', 'completed')->where('to',$reference1)->first(['id']);
                $reference_2_called = CallLogs::where('_id', $consumer_applications->id)->where('id_type','application_id')->where('status', 'completed')->where('to', $reference2)->first(['id']);
                if (isset($reference_1_called->id) && !empty($reference_1_called->id) && isset($reference_2_called->id) && !empty($reference_2_called->id)) {
                    return true;
                }

            }elseif (isset($consumer_applications->application_element->reference_contact_1) && !empty($consumer_applications->application_element->reference_contact_1)){

                $reference1 = $consumer_applications->application_element->reference_contact_1;

                $reference_called = CallLogs::where('_id', $consumer_applications->id)->where('id_type','application_id')->where('status', 'completed')->where('to', $reference1)->first(['id']);
                if (isset($reference_called->id) && !empty($reference_called->id)) {
                    return true;
                }

            }elseif (isset($consumer_applications->application_element->reference_contact_2) && !empty($consumer_applications->application_element->reference_contact_2)){
                $reference2 = $consumer_applications->application_element->reference_contact_2;

                $reference_called = CallLogs::where('_id', $consumer_applications->id)->where('id_type','application_id')->where('status', 'completed')->where('to', $reference2)->first(['id']);
                if (isset($reference_called->id) && !empty($reference_called->id)) {
                    return true;
                }
            }

        }
    }

    public function auditTrail($id, $type){//type as in merchant or customer

        if ($type == 'merchant') {
            $merchant_data = Merchant::with('digital_sign')->where('id', $id)->first();
            if(isset($merchant_data) && isset($merchant_data->digital_sign) && $merchant_data->digital_sign) {
                if (isset($merchant_data->digital_sign->isagreementsigned) && $merchant_data->digital_sign->isagreementsigned == 1) {
                    $name = $merchant_data->merchant_name;
                    $smsLogs = SMSLogs::where('mobile_number', '91'.$merchant_data->contact_number)->where('message','like','%Your+Creditfair+verification+code+is+%')->orderBy('created_at','desc')->first(['created_at','message']);
                    $otp_sent = isset($smsLogs->created_at) ? $smsLogs->created_at : '';
                    $otp_verified = '';
                    if($otp_sent) {
                        $OtpManager = OtpManager::onlyTrashed()->where('mobile_number', $merchant_data->contact_number)->where('otp', str_replace('Your+Creditfair+verification+code+is+', '', $smsLogs->message))->orderBy('deleted_at','desc')->first(['deleted_at']);
                        $otp_verified = isset($OtpManager->deleted_at) ? $OtpManager->deleted_at : '';
                    }
                    $view = view('admin.consumer-application.audit_trails', ['otp_sent' => $otp_sent, 'otp_verified' => $otp_verified, 'data' => $merchant_data->digital_sign, 'm_email' => $merchant_data->email, 'agreement_signed_by' => $merchant_data->agreement_signed_by, 'm_mobile_number' => $merchant_data->contact_number, 'name' => $name, 'type' => 'merchant']);
                    $pdf = App::make('snappy.pdf.wrapper');
                    return  $pdf->loadHTML($view)->output();
                }
            }

        } else {

            $application_data = ConsumerApplication::with('digital_sign','merchant')->where('id', $id)->first();

            if($application_data->digital_sign) {
                $applicant_name = $application_data->name;
                $co_applicant_name = $application_data->co_applicant_name;

                $otp_sent = '';
                $otp_verified = '';
                $otp_verified_co = '';
                $otp_sent_co = '';
                if(isset($application_data->merchant->remove_esign_otp) && $application_data->merchant->remove_esign_otp == 0) {

                    $smsLogs = SMSLogs::where('mobile_number', '91' . $application_data->mobile_number)->where('message', 'like', '%Your+Creditfair+verification+code+is+%')->orderBy('created_at', 'desc')->first(['created_at', 'message']);
                    $otp_sent = isset($smsLogs->created_at) ? $smsLogs->created_at : '';
                    if ($otp_sent) {
                        $OtpManager = OtpManager::onlyTrashed()->where('mobile_number', $application_data->mobile_number)->where('otp', str_replace('Your+Creditfair+verification+code+is+', '', $smsLogs->message))->orderBy('deleted_at', 'desc')->first(['deleted_at']);
                        $otp_verified = isset($OtpManager->deleted_at) ? $OtpManager->deleted_at : '';
                    }

                    if ($co_applicant_name) {
                        $smsLogs = SMSLogs::where('mobile_number', '91' . $application_data->co_applicant_mobile_number)->where('message', 'like', '%Your+Creditfair+verification+code+is+%')->orderBy('created_at', 'desc')->first(['created_at', 'message']);
                        $otp_sent_co = isset($smsLogs->created_at) ? $smsLogs->created_at : '';
                        if ($otp_sent) {
                            $OtpManager = OtpManager::onlyTrashed()->where('mobile_number', $application_data->co_applicant_mobile_number)->where('otp', str_replace('Your+Creditfair+verification+code+is+', '', $smsLogs->message))->orderBy('deleted_at', 'desc')->first(['deleted_at']);
                            $otp_verified_co = isset($OtpManager->deleted_at) ? $OtpManager->deleted_at : '';
                        }
                    }
                }


                $view = view('admin.consumer-application.audit_trails', ['otp_sent' => $otp_sent, 'otp_verified' => $otp_verified, 'otp_sent_co' => $otp_sent_co, 'otp_verified_co' => $otp_verified_co,'data' => $application_data->digital_sign, 'applicant_name' => $applicant_name, 'co_applicant_name' => $co_applicant_name, 'email' => $application_data->email, 'mobile_number' => $application_data->mobile_number, 'co_email' => $application_data->co_applicant_email, 'co_mobile_number' => $application_data->co_applicant_mobile_number, 'type' => 'consumer']);
                $pdf = App::make('snappy.pdf.wrapper');
                return $pdf->loadHTML($view)->output();
            }

        }
        return false;
    }

    public function regenerateDocuments($application_id){
        $application = ApplicationEMICalculationLock::where('application_id', $application_id)->orderBy('created_at','desc')->limit(2)->get();
        if(count($application) > 1){
            if ($application[0]->approved_amount && $application[1]->approved_amount && $application[0]->approved_amount != $application[1]->approved_amount){
                event(new EventPostCreateCustomer($application_id));
            }
        }
    }

    public function requestHypervergeKYC($id, $ret = 'res'){
        try {
            $application = ConsumerApplication::where('id', $id)->first(['id', 'pan_card', 'dob', 'name','co_applicant_pan_card','co_applicant_dob','co_applicant_name','lender_id']);
            if(!$application->pan_card) {
                if ($ret === 'res') {
                    return \response()->json(['status' => 'FAIL', 'message' => 'Pan card number required'], 200);
                } else {
                    return ['status' => 'FAIL', 'message' => 'Pan card number required'];
                }
            }

            if(!$application->dob) {
                if ($ret === 'res') {
                    return \response()->json(['status' => 'FAIL', 'message' => 'Date of birth required'], 200);
                } else {
                    return ['status' => 'FAIL', 'message' => 'Date of birth required'];
                }

            }

            if($application->co_applicant_name){
                if(!$application->co_applicant_pan_card) {
                    if ($ret === 'res') {
                        return \response()->json(['status' => 'FAIL', 'message' => 'Co-Applicant Pan card number required'], 200);
                    } else {
                        return ['status' => 'FAIL', 'message' => 'Co-Applicant Pan card number required'];
                    }

                }
                if(!$application->co_applicant_dob) {
                    if ($ret === 'res') {
                        return \response()->json(['status' => 'FAIL', 'message' => 'Co-Applicant Date of birth required'], 200);
                    } else {
                        return ['status' => 'FAIL', 'message' => 'Co-Applicant Date of birth required'];
                    }

                }
            }

            $hypervergeVideo = new HypervergeVideo(new Request(['application' => $application]));

            $data = [];
            if(false !== ($data = $hypervergeVideo->getRequestedAttributes())) {
                //return \response()->json(array_merge(['status' => 'OK'], $data), 200);
            } else {
                $data = $hypervergeVideo->getVideoKYCURL();
            }

            if ($ret === 'res') {
                return \response()->json(array_merge(['status' => 'OK'], $data), 200);
            } else {
                return array_merge(['status' => 'OK'], $data);
            }

        }catch (\Exception $e){
            if ($ret === 'res') {
                return \response()->json(['status' => 'FAIL', 'message' => 'Exception occurred while requesting Hyperverge video KYC'], 200);
            } else {
                return ['status' => 'FAIL', 'message' => 'Exception occurred while requesting Hyperverge video KYC'];
            }

        }
    }

    public function sendUtkarshKYC(Request $request, $id){
        try {
            // return \response()->json(['status' => 'OK', 'message' => 'Successfully sent the video kyc link', 'data' => $request->all()], 200);
            if ($id) {
                $kyc = UtkarshVKYC::where('application_id', $id)->where('applicant_type', $request->get('applicant_type'))->first(['id', 'response']);
                if(!isset($kyc->id)){
                    $request->merge(['id' => $id,'application_id' => $id, 'applicant_type' => $request->get('applicant_type')]);
                    $utkarsh = new Utkarsh($request);
                    if($url = $utkarsh->getKYCLink()){
                        if(isset($url->code)){
                            return \response()->json(['status' => 'FAIL', 'message' => $url->message], 200);
                        }
                        if($request->has('kyc_link_only') && $request->get('kyc_link_only')){
                            return \response()->json(['status' => 'OK', 'message' => 'URL Fetched successfully', 'url' => $url], 200);
                        }else{
                            //Send EKYC Link, custome will be redirected to VKYC after EKYC
                            $hash = new Hashids('Creditfair by CS', 20);
                            $hashed_id_app = $hash->encode($id);
                            $hashed_id_co_app = $hash->encode($request->get('applicant_type'));
                            $url = asset('customer/kyc/'.$hashed_id_app.'/'.$hashed_id_co_app);
                        }
                        $this->sendUtkarshVKYCLink($id, $url);
                    }else{
                        return \response()->json(['status' => 'FAIL', 'message' => $utkarsh->error ?? 'Failed to get the VKYC link'], 200);
                    }
                }
                return \response()->json(['status' => 'OK', 'message' => 'Successfully sent the video kyc link', 'url' => isset($kyc->response) ? json_decode($kyc->response)->waitPageUrl : $url], 200);
            } else {
                return \response()->json(['status' => 'FAIL', 'message' => 'Invalid parameters'], 200);
            }
        }catch (\Exception $e){
            return \response()->json(['status' => 'FAIL', 'message' => $e->getMessage().'|'.$e->getLine().'|'.$e->getFile()], 200);
        }
    }

    public function sendUtkarshVKYCLink($id, $link){
        $application = ConsumerApplication::where('id', $id)->first(['id', 'lender_id', 'email']);
        if(isset($application->email) && $application->email) {
            $email = $application->email;
            $emailBody = "Dear " . $application->name . ",<br/>Congratulations on the approval of your loan application.<br/>Please complete the KYC process by clicking on the link " . $link . " <br/>
                Instructions for VKYC:
                <ul>
                    <li>Share the PAN Card (original/e-Pan/ Digilocker) details of the Financial Applicant only</li>
                    <li>Provide your physical & original documents while doing VKYC</li>
                </ul>
                </br> Thanks, Team Credit Fair";

            if ($email) {
                Mail::send('emails.reminders.basic_reminder',
                    [
                        'body' => $emailBody,
                        'lender_id' => $application->lender_id
                    ]
                    , function ($message) use ($email) {
                        $message->to($email)->subject('Video KYC - Credit Fair');
                    });
            }
        }
    }

    public function sendHypervergeKYC(Request $request, $id) {
        try {
            // return \response()->json(['status' => 'OK', 'message' => 'Successfully sent the video kyc link', 'data' => $request->all()], 200);
            if ($request->has('customer_link') || $request->has('co_customer_link')) {
                $email = '';
                $mobile = '';
                if($request->get('applicant_type') == 1) {
                    $application = ConsumerApplication::with('application_element', 'application_additional')->where('id', $id)->first(['id', 'email', 'mobile_number', 'name','lender_id']);
                    if (!$application->email && !$application->mobile_number) {
                        return \response()->json(['status' => 'FAIL', 'message' => 'Email or Mobile number required'], 200);
                    }
                    $email = $application->email;
                    if(isset($application->application_additional) && isset($application->application_additional->linked_status) && $application->application_additional->linked_status == 1){
                        $mobile = $application->mobile_number ? $application->mobile_number : '';
                    }else if(isset($application->application_additional) && isset($application->application_additional->linked_mobile_to_aadhar_status) && $application->application_additional->linked_mobile_to_aadhar_status == 1){
                        $mobile = $application->aadhar_linked_mobile ? $application->aadhar_linked_mobile : '';
                    }

                }else{
                    $application = ConsumerApplication::with('application_element','application_additional')->where('id', $id)->first(['id', 'co_applicant_email', 'co_applicant_mobile_number','co_applicant_name as name','lender_id']);
                    if (!$application->co_applicant_email && !$application->co_applicant_mobile_number) {
                        return \response()->json(['status' => 'FAIL', 'message' => 'Email or Mobile number required'], 200);
                    }
                    $email = $application->co_applicant_email;

                    if(isset($application->application_additional) && isset($application->application_additional->linked_status) && $application->application_additional->linked_status == 1){
                        $mobile = $application->co_applicant_mobile_number ? $application->co_applicant_mobile_number : '';
                    }else if(isset($application->application_additional) && isset($application->application_additional->coapp_linked_mobile_to_aadhar_status) && $application->application_additional->coapp_linked_mobile_to_aadhar_status == 1){
                        $mobile = $application->application_additional->coapplicant_aadhar_linked_mobile ? $application->application_additional->coapplicant_aadhar_linked_mobile : '';
                    }
                }

                if($mobile == ''){
                    return \response()->json(['status' => 'FAIL', 'message' => 'Mobile number not linked to aadhar'], 200);
                }

                $link = $request->get('applicant_type') == 1 ? $request->get('customer_link') : $request->get('co_customer_link');
                $messageBody = "Dear ".$application->name.",<br/>Congratulations on the approval of your loan application.<br/>Please complete the KYC process by clicking on the link below: ". $link." Thanks, Team Credit Fair";

                $emailBody = "Dear ".$application->name.",<br/>Congratulations on the approval of your loan application.<br/>Please complete the KYC process by clicking on the link ". $link." <br/>
                Instructions for VKYC:
                <ul>
                    <li>Share the PAN Card (original/e-Pan/ Digilocker) details of the Financial Applicant only</li>
                    <li>Provide your physical & original documents while doing VKYC</li>
                </ul>
                </br> Thanks, Team Credit Fair";
                $entity = ['templateid' => '1307161725614153380', 'entityid' => Templates::$entityid];
                if ($email) {
                    Mail::send('emails.reminders.basic_reminder',
                        [
                            'body' => $emailBody,
                            'lender_id' => $application->lender_id
                        ]
                        , function ($message) use ($email) {
                            $message->to($email)->subject('Video KYC - Credit Fair');
                        });
                }

                if ($mobile && $request->get('applicant_type') == 1) {
                    send_sms($mobile, ['message' => $messageBody, 'templateDetails' => $entity,'id' => $id, 'id_type' => 'application_id']);
                }else if ($mobile && $request->get('applicant_type') == 2) {
                    send_sms($mobile, ['message' => $messageBody, 'templateDetails' => $entity,'id' => $id, 'id_type' => 'application_id']);
                }
                return \response()->json(['status' => 'OK', 'message' => 'Successfully sent the video kyc link'], 200);
            } else {
                return \response()->json(['status' => 'FAIL', 'message' => 'Invalid parameters'], 200);
            }
        }catch (\Exception $e){
            return \response()->json(['status' => 'FAIL', 'message' => 'Exception occurred while sending Hyperverge video KYC link'], 200);
        }
    }

    public function sendAgreementToVendor($vendor, $appObj) {
        try {
            switch($vendor) {
                case 'digio':
                    return LoanAgreementVendor::sendLoanAgreementToVendor($vendor, $appObj);
                    break;
            }
        } catch (\Exception $e) {
            (new Slack(new Request(['title'=>"Loan agreement was not sent to esign vendor ".$vendor, 'fields'=>['Message' => $e->getMessage(), 'Line' => $e->getLine(), 'File' =>$e->getFile(), 'Trace' => $e->getTraceAsString()]])))->send();
            return false;
        }

    }
    public function getAvanseData($id){
        return (new AvanseProcesses(new Request()))->getAvanseSummary($id);
    }

    // public function getSentApplicationToAvanse($id) {
    //     //try {
    //         //if($request->ajax()){
    //             //$inputs = $request->all();
    //             // if(empty($inputs['app_id'])) {
    //             //     return \response()->json(['status' => 'failed','error' => 'Invalid inputs'], 200);
    //             // }
    //             // $request = new Request();
    //             // $request->request->add([
    //             //     //'type' => 'Sanction Letter',
    //             //     'bot' => true,
    //             //     'test_bot' => false,
    //             //     'from_mail' => env('CENTRALOPS')
    //             // ]);

    //             // $document = (new ConsumerDocument($request));
    //             // $documentDetails = $document->getDocument($id);
    //             // Mail::send('emails.reminders.basic_reminder', [
    //             //         'body' => view('emails.reminders.send_to_avanse', $documentDetails),
    //             //         'lender_id' => $documentDetails['lender']['id'],
    //             //         'is_include_footer' => false
    //             //     ], function ($message) use ($id) {
    //             //         $message->to('gaurav@creditfair.in')->subject('Your loan application '.$id.' has been approved');
    //             //     });


    //             // generate DA and send to merchant
    //             $this->sendProForma($id, false, true);

    //             // generate CAM and upload it to S3
    //             //$this->generateCAMReport($appObj->id);

    //             return "Done";
    //         //}
    //         //return \response()->json(['status' => 'failed','error' => 'Invalid request'], 200);
    //     // } catch (\Exception $e) {
    //     //     (new Slack(new Request(['title'=>"Send to avanse failed", 'fields'=>['Message' => $e->getMessage(), 'Line' => $e->getLine(), 'File' =>$e->getFile(), 'Trace' => $e->getTraceAsString()]])))->send();
    //     //     return false;
    //     // }
    // }

    public function approvalCommunication($application_id){
        try{
            $application_status = ConsumerApplication::with('activeOffer', 'emi')->where('id', $application_id)->first(['id', 'lender_id','user_id','merchant_id','state', 'name', 'mobile_number', 'email', 'approved_amount', 'loan_amount','pan_card','aadhaar_card','co_applicant_pan_card','co_applicant_aadhaar_card','merchant_id','co_applicant_mobile_number','co_applicant_name','co_applicant_email','offer_id']);
            $this->initiateForLatestBankStatement($application_id);
            $this->saveLiabilityPercent($application_status, $application_id, 'job');
            $this->checkApprovedPinCode($application_id);
            $this->ApprovalInit($application_status, $application_id);
            $this->disbursementOffers($application_id);
            $this->sendemandate($application_id);
            $isError = $this->sendSanctionLetter($application_id);
            $this->proformaSigningNotification($application_id);
            $this->creditLimitNotification($application_id);
            $this->sendProForma($application_id);
//            $this->insertIntoJob($application_id, 'referral_communication', $status);
//            $this->whatsAppCommunication($application_status, $status);
        } catch (\Exception $e) {
            (new Slack(new Request(['title'=>"Failed to send communication", 'fields'=>['application_id' => $application_id, 'Message' => $e->getMessage(), 'Line' => $e->getLine(), 'File' =>$e->getFile(), 'Trace' => $e->getTraceAsString()]])))->send();
            return false;
        }
    }

    public function runMarkytics($application_id){
        try{
            $finbit = (new FinBit(new Request(['id'=>$application_id])))->markyticsEventTrigger();
            return response()->json(['status' => 'OK'], 200);
        }catch (\Exception $e) {
            return response()->json(['status' => 'FAIL']);
        }
    }

    public function matchAddress($consumer_applications){
        $current_address_percentage = 0;
        $current_address_percentageArray = [0];
        $data = [];
        $address_percentage = 0;
        $esign_address_percentage = 'Unable to fetch address';
        $match_esign = 'Unable to fetch pincode';

        // <!-- current address with bureau address -->
        foreach($consumer_applications->creditReport as $report){
            if($report) {
                if ($report->applicant_type == 1 && $consumer_applications->current_address_line_1 && $report->AddressInfoList != "null") {
                    $addressLists = ($report->AddressInfoList != null) ? json_decode($report->AddressInfoList, 1) : [];

                    $current_address_bureau = $consumer_applications->current_address_line_1. ' ' . $consumer_applications->current_address_landmark . ' ' . $consumer_applications->current_address_state . ' ' . $consumer_applications->current_address_city . ' ' . $consumer_applications->current_address_pincode;
                    $current_pincode_bureau = $consumer_applications->current_address_pincode;

                    foreach ($addressLists as $addressList) {
                        if (isset($addressList['Address'])) {
                            $pin = isset($addressList['Postal']) ? $addressList['Postal'] : '';
                            similar_text(strtolower($current_address_bureau), strtolower($addressList['Address'] . ' ' . $pin), $current_address_percentage);
                            $pinmatch = similar_text(strtolower($current_pincode_bureau), strtolower($pin));
                            $current_address_percentageArray[] = round($current_address_percentage);
                            $current_pincode_matchArray[] = $pinmatch;
                        }
                    }
                }

                if(isset($current_pincode_matchArray) && max($current_pincode_matchArray) == 6){
                    $match_bureau = '<i class="fa fa-check"></i> Matched with Bureau Pincode';
                }else{
                    $match_bureau = '<i class="fa fa-close"></i> Not Matched with Bureau Pincode';
                }

                if ($report->applicant_type == 1) {
                    $data['current_contact_bureau'] = ['matched_address' => max($current_address_percentageArray).'% Matched With Bureau Address','matched_pincode' => $match_bureau];
                }
            }
        }

        // <!-- current address with esign address -->
        $userGeolocationEsign = UserGeolocation::where('_id', $consumer_applications->id)->where('id_type', 'application_id')->where('service','esign')->whereNull('deleted_at')->first(['id', 'latitude', 'longitude']);

        if($userGeolocationEsign != []){
            $geoAddress = $this->Get_Address_From_Google_Maps($userGeolocationEsign['latitude'], $userGeolocationEsign['longitude']);

            if($geoAddress != []){
                $current_address_esign = $consumer_applications->current_address_line_1. ' ' . $consumer_applications->current_address_landmark . ' ' . $consumer_applications->current_address_city . ' ' . $consumer_applications->current_address_state. ' '.$consumer_applications->current_address_pincode;
                $current_pincode_esign = $consumer_applications->current_address_pincode;

                similar_text(strtolower($current_address_esign), strtolower($geoAddress['formatted_address']), $esign_address_percentage);
                $current_pincode_esign_match = similar_text(strtolower($current_pincode_esign), strtolower($geoAddress['postal_code']));

                if($esign_address_percentage){
                    $esign_address_percentage = round($esign_address_percentage).'% Matched with E-Signing Location';
                }

                if($current_pincode_esign_match == 6){
                    $match_esign = '<i class="fa fa-check"></i> Matched with E-Signing Location';
                }else{
                    $match_esign = '<i class="fa fa-close"></i> Not Matched with E-Signing Location';
                }
            }
            $data['current_contact_esign'] = ['matched_address' => $esign_address_percentage, 'matched_pincode' => $match_esign];
        }

        // <!-- current address with permanent address -->
        $current_address = $consumer_applications->current_address_line_1. ' ' . $consumer_applications->current_address_landmark . ' ' . $consumer_applications->current_address_state . ' ' . $consumer_applications->current_address_city . ' ' . $consumer_applications->current_address_pincode;
        $current_pincode = $consumer_applications->current_address_pincode;
        // handle when $current_address contains space only
        if (strlen(trim($current_address)) == 0) {
            $current_address = '';
        }

        $permanent_address = $consumer_applications->permanent_address_line_1 .' '.$consumer_applications->permanent_address_landmark. ' ' . $consumer_applications->permanent_address_state . ' ' . $consumer_applications->permanent_address_city . ' ' . $consumer_applications->permanent_address_pincode;
        $permanent_pincode = $consumer_applications->permanent_address_pincode;
        // handle when $permanent_address contains space only
        if (strlen(trim($permanent_address)) == 0) {
            $current_address = '';
        }

        similar_text(strtolower($current_address), strtolower($permanent_address), $address_percentage);
        $match_pincode = similar_text(strtolower($current_pincode), strtolower($permanent_pincode));

        if($match_pincode == 6){
            $match = '<i class="fa fa-check"></i> Matched with Permanent Pincode';
        }else{
            $match = '<i class="fa fa-close"></i> Not Matched with Permanent Pincode';
        }

        $data['current_contact'] = ['matched_address' => round($address_percentage).'% Matched with Permanent Address', 'matched_pincode' => $match];
        return $data;
    }

    public function dailyCronJobForExcelMail(){
        $excelData = \DB::select("with files as (select consumer_application_id,
        sum(case when file_type in ('emandate','e mandate') then 1 else 0 end) mandate,
        sum(case when file_type = 'pro_forma_invoice' then 1 else 0 end) da_accepted,
        sum(case when file_type in ('digio report applicant','digio report coapplicant') then 1 else 0 end) digio_done,
        sum(case when file_type = 'loan_agreement_esign' then 1 else 0 end) esign_done,
        sum(case when file_type in ('karzaV_report_applicant','karzaV_report_coapplicant') then 1 else 0 end) vkyc_done
        from consumer_application_files
        where file_type in ('emandate','e mandate','pro_forma_invoice','digio report applicant','digio report coapplicant',
        'loan_agreement_esign','karzaV_report_applicant','karzaV_report_coapplicant')
        group by consumer_application_id),
        app_status as (select sl.application_id, sl.status, sl.created_at, 
        case when sl.status='approved' then cm.name else null end credit_manager,
        coalesce(lead(sl.created_at , 1) over (partition by sl.application_id order by sl.id),CONVERT_TZ(NOW(),'SYSTEM','Asia/Calcutta')) created_at_next from status_logs sl
        left join users cm on cm.id = sl.user_id),
        app_status_tat as (select credit_manager, application_id, status, created_at , created_at_next , 
        TIMESTAMPDIFF(SECOND,created_at,created_at_next) tat_hrs
        from app_status), total_tat as (
        select application_id, 
        max(credit_manager) credit_manager,
        sum(case when status = 'incomplete form' then 1 else 0 end) incomplete_form_count,
        sum(case when status = 'incomplete form' then tat_hrs else 0 end) incomplete_form_tat,
        sum(case when status = 'form completed' then 1 else 0 end) form_completed_count,
        sum(case when status = 'form completed' then tat_hrs else 0 end) form_completed_tat,
        sum(case when status = 'in-process' then 1 else 0 end) in_process_count,
        sum(case when status = 'in-process' then tat_hrs else 0 end) in_process_tat,
        sum(case when status = 'waiting for documents' then 1 else 0 end) waiting_for_documents_count,
        sum(case when status = 'waiting for documents' then tat_hrs else 0 end) waiting_for_documents_tat,
        sum(case when status = 'waiting for decision' then 1 else 0 end) waiting_for_decision_count,
        sum(case when status = 'waiting for decision' then tat_hrs else 0 end) waiting_for_decision_tat,
        sum(case when status = 'pre approved' then 1 else 0 end) pre_approved_count,
        sum(case when status = 'pre approved' then tat_hrs else 0 end) pre_approved_tat,
        sum(case when status = 'cf approved' then 1 else 0 end) cf_approved_count,
        sum(case when status = 'cf approved' then tat_hrs else 0 end) cf_approved_tat,
        sum(case when status = 'approved' then 1 else 0 end) approved_count,
        sum(case when status = 'approved' then tat_hrs else 0 end) approved_tat,
        sum(case when status = 'disbursement checklist done' then 1 else 0 end) disbursement_checklist_done_count,
        sum(case when status = 'disbursement checklist done' then tat_hrs else 0 end) disbursement_checklist_done_tat,
        sum(case when status = 'disbursement query' then 1 else 0 end) disbursement_query_count,
        sum(case when status = 'disbursement query' then tat_hrs else 0 end) disbursement_query_tat,
        sum(case when status = 'ready for disbursement' then 1 else 0 end) ready_for_disbursement_count,
        sum(case when status = 'ready for disbursement' then tat_hrs else 0 end) ready_for_disbursement_tat,
        sum(case when status = 'disbursed' then tat_hrs else 0 end) disbursed_tat
        from app_status_tat group by application_id),
        app_tat as (select application_id, credit_manager,
        incomplete_form_count, 
        concat(floor(incomplete_form_tat/86400),'-' , sec_to_time((incomplete_form_tat - (floor(incomplete_form_tat/86400)*86400)))) incomplete_form_tat,
        form_completed_count, 
        concat(floor(form_completed_tat/86400),'-' , sec_to_time((form_completed_tat - (floor(form_completed_tat/86400)*86400)))) form_completed_tat,
        in_process_count, 
        concat(floor(in_process_tat/86400),'-' , sec_to_time((in_process_tat - (floor(in_process_tat/86400)*86400)))) in_process_tat,
        waiting_for_documents_count, 
        concat(floor(waiting_for_documents_tat/86400),'-' , sec_to_time((waiting_for_documents_tat - (floor(waiting_for_documents_tat/86400)*86400)))) waiting_for_documents_tat,
        waiting_for_decision_count, 
        concat(floor(waiting_for_decision_tat/86400),'-' , sec_to_time((waiting_for_decision_tat - (floor(waiting_for_decision_tat/86400)*86400)))) waiting_for_decision_tat,
        pre_approved_count, 
        concat(floor(pre_approved_tat/86400),'-' , sec_to_time((pre_approved_tat - (floor(pre_approved_tat/86400)*86400)))) pre_approved_tat,
        cf_approved_count, 
        concat(floor(cf_approved_tat/86400),'-' , sec_to_time((cf_approved_tat - (floor(cf_approved_tat/86400)*86400)))) cf_approved_tat,
        approved_count, 
        concat(floor(approved_tat/86400),'-' , sec_to_time((approved_tat - (floor(approved_tat/86400)*86400)))) approved_tat,
        disbursement_checklist_done_count, 
        concat(floor(disbursement_checklist_done_tat/86400),'-' , sec_to_time((disbursement_checklist_done_tat - (floor(disbursement_checklist_done_tat/86400)*86400)))) disbursement_checklist_done_tat,
        disbursement_query_count, 
        concat(floor(disbursement_query_tat/86400),'-' , sec_to_time((disbursement_query_tat - (floor(disbursement_query_tat/86400)*86400)))) disbursement_query_tat,
        ready_for_disbursement_count, 
        concat(floor(ready_for_disbursement_tat/86400),'-' , sec_to_time((ready_for_disbursement_tat - (floor(ready_for_disbursement_tat/86400)*86400)))) ready_for_disbursement_tat,
         concat(floor(disbursed_tat/86400),'-' , sec_to_time((disbursed_tat - (floor(disbursed_tat/86400)*86400)))) disbursed_tat
         from total_tat),
        comments as (select z.application_id, z.created_at last_comment_date, z.comment last_comment, z.commenter_name last_commenter_name  
        from (select rank() over (partition by application_id order by id desc) rk, u.name commenter_name, c.* from comments c
        left join users u on c.user_id = u.id
        ) z where z.rk=1),
        credit_report as (select z.application_id, z.score bureau_score, z.created_at bureau_pull_date from (select rank() over (partition by application_id order by id desc) rk,  cr.* from credit_report cr
        ) z where z.rk=1),
        calls as (select z._id application_id, z.created_at last_call_time, z.purpose last_call_purpose, z.caller_receiver_name last_caller_receiver_name  from (
        select rank() over (partition by _id order by id desc) rk, u.name caller_receiver_name, cl.* from call_logs cl
        left join users u on cl.user_id = u.id
        ) z where z.rk=1)
        select ca.id as id, ca.updated_by as application_source, le.name as lender_name, ca.name as name, ca.loan_amount, ca.approved_amount, m.merchant_name as merchant_name, mc.name as merchant_category, ca.purpose as purpose, ml.name as center, 
        u.name as advisor, ca.created_at AS application_date, ca.state as state, c.last_comment_date as last_comment_date, 
        DATEDIFF(current_date(),c.last_comment_date) as days_since_last_comment, c.last_comment as last_comment, c.last_commenter_name as last_commenter_name,
        cl.last_call_time as last_call, DATEDIFF(current_date(),cl.last_call_time) as days_since_last_call, 
        cl.last_call_purpose as last_call_purpose, cl.last_caller_receiver_name as last_caller_receiver,
        f.mandate as mandate_status, f.da_accepted as da_accepted, f.digio_done as digio_done, f.esign_done as esign_done, f.vkyc_done as vkyc_done, cr.bureau_pull_date as bureau_pull_date, cr.bureau_score as bureau_score , 
        tat.credit_manager as credit_manager, tat.incomplete_form_count as incomplete_form_count, tat.incomplete_form_tat as incomplete_form_tat, tat.form_completed_count as form_completed_count, tat.form_completed_tat as form_completed_tat, 
        tat.in_process_count as in_process_count, tat.in_process_tat as in_process_tat, tat.waiting_for_documents_count as waiting_for_documents_count, tat.waiting_for_documents_tat as waiting_for_documents_tat, tat.waiting_for_decision_count as waiting_for_decision_count, 
        tat.waiting_for_decision_tat as waiting_for_decision_tat, tat.pre_approved_count as pre_approved_count, tat.pre_approved_tat as pre_approved_tat, tat.cf_approved_count as cf_approved_count, tat.cf_approved_tat as cf_approved_tat, approved_count, 
        tat.approved_tat as approved_tat, tat.disbursement_checklist_done_count as disbursement_checklist_done_count, tat.disbursement_checklist_done_tat as disbursement_checklist_done_tat, tat.disbursement_query_count as disbursement_query_count, tat.disbursement_query_tat as disbursement_query_tat, tat.ready_for_disbursement_count as ready_for_disbursement_count, 
        tat.ready_for_disbursement_tat as ready_for_disbursement_tat
        from consumer_application ca 
        LEFT JOIN merchant m ON m.id = ca.merchant_id
        LEFT JOIN lenders le ON le.id = ca.lender_id
        LEFT JOIN consumer_application_element cae ON cae.application_id = ca.id
        LEFT join credit_report cr on cr.application_id=ca.id
        LEFT JOIN merchant_location ml ON ml.id = cae.center_id
        LEFT JOIN users u ON u.id = ca.created_by
        INNER JOIN merchant_category mc ON mc.id = ca.purpose and mc.name !='Personal Loan'
        LEFT JOIN comments c on c.application_id=ca.id
        LEFT JOIN calls cl on ca.id=cl.application_id
        left join app_tat tat on tat.application_id=ca.id
        left join files f on f.consumer_application_id = ca.id
        where ca.state in ('incomplete form','form completed','in-process','waiting for documents','waiting for decision','pre approved','cf approved','approved','ready for disbursement','disbursement checklist done','disbursement query')
        and ca.is_deleted is null;");

    $header[] = ['Id', 'Lender Name', 'Name', 'Loan Amount', 'Approved Amount', 'Merchant Name', 'Category Name','Purpose','Center','Advisor','Application Date','Application State',/*'Last Status','In Process Days','Approved Days',*/'Last Comment','Days Since Last Comment','Commented By','Days Since Last Call','Purpose- Last Call','Caller/Receiver',/*'Last Status Time','Last Status Name','iKyc Done',*/'Vkyc Done','Digio Done','Mandate Done','Agreement Signed','DA Accepted','Bureau Pulled','Bureau Score','Credit Manager','incomplete form count','incomplete form tat','form completed count','in process count','in process tat','waiting for documents count','waiting for documents tat','waiting for decision count','waiting for decision tat','pre approved count','pre approved tat','cf approved count','cf approved tat','approved count','approved tat','disbursement checklist done count','disbursement checklist done tat','disbursement query count','disbursement query tat','ready for disbursement count','ready for disbursement tat'];

    if(isset($excelData)){
        foreach($excelData as $keyitem => $excelItem) {
            $response[] = [
                'id' => $excelItem->id,
                'lender_name' => $excelItem->lender_name,
                'name' => $excelItem->name,
                'loan_amount' => $excelItem->loan_amount,
                'approved_amount' => $excelItem->approved_amount,
                'merchant_name' => $excelItem->merchant_name,
                'category_name' => $excelItem->merchant_category,
                'purpose' => $excelItem->purpose,
                'center' => $excelItem->center,
                'advisor' => $excelItem->advisor,
                'application date' => $excelItem->application_date,
                'application state' => $excelItem->state,
                // 'last status' => $excelItem->Last_status,
                // 'in process days' => $excelItem->in_process_tat,
                // 'approved days' => $excelItem->approved_tat,
                'last comment' => $excelItem->last_comment,
                'days since last comment' => $excelItem->days_since_last_comment,
                'commented by' => $excelItem->last_commenter_name,
                'days since last call' => $excelItem->days_since_last_call,
                'purpose- last call' => $excelItem->last_call_purpose,
                'caller/receiver' => $excelItem->last_caller_receiver,
                // 'last status time' => $excelItem->Last_Status_Changed_time,
                // 'last status name' => $excelItem->Last_Status_Changed_by,
                // 'ikyc done' => (($excelItem->poa_masked + $excelItem->poi_masked) >= 3) ? 'yes' : 'no',
                'vkyc done' => $excelItem->vkyc_done,
                'digio done' => $excelItem->digio_done,
                'mandate done' => $excelItem->mandate_status,
                'agreement signed' => $excelItem->esign_done,
                'da accepted' => $excelItem->da_accepted,
                'bureau pulled' => isset($excelItem->bureau_pull_date) ? 'yes' : 'no',
                'bureau score' => $excelItem->bureau_score,
                'credit manager' => $excelItem->credit_manager,
                'incomplete form count' => $excelItem->incomplete_form_count,
                'incomplete form tat' => $excelItem->incomplete_form_tat,
                'form completed count' => $excelItem->form_completed_count,
                'in process count' => $excelItem->in_process_count,
                'in process tat' => $excelItem->in_process_tat,
                'waiting for documents count' => $excelItem->waiting_for_documents_count,
                'waiting for documents tat' => $excelItem->waiting_for_documents_tat,
                'waiting for decision count' => $excelItem->waiting_for_decision_count,
                'waiting for decision tat' => $excelItem->waiting_for_decision_tat,
                'pre approved count' => $excelItem->pre_approved_count,
                'pre approved tat' => $excelItem->pre_approved_tat,
                'cf approved count' => $excelItem->cf_approved_count,
                'cf approved tat' => $excelItem->cf_approved_tat,
                'approved count' => $excelItem->approved_count,
                'approved tat' => $excelItem->approved_tat,
                'disbursement checklist done count' => $excelItem->disbursement_checklist_done_count,
                'disbursement checklist done tat' => $excelItem->disbursement_checklist_done_tat,
                'disbursement query count' => $excelItem->disbursement_query_count,
                'disbursement query tat' => $excelItem->disbursement_query_tat,
                'ready for disbursement count' => $excelItem->ready_for_disbursement_count,
                'ready for disbursement tat' => $excelItem->ready_for_disbursement_tat
            ];
        }
        $request = new Request(['data' => array_merge($header, $response), 'sheet' => 'Sheet1']);
        $date = Carbon::now()->toDateString();
        $file = 'Daily Excel File_' . $date . '.xls';
        Excel::store(new Exporter($request), $file);

        $mail_ids = _env('APP_CONNECTION') ? ['rohit@creditfair.in', 'rohan@creditfair.in', 'shraddha@credtifair.in', 'aditya@creditfair.in'] : ['himanshubamania@creditfair.in', 'pratik@creditfair.in', 'suyog@creditfair.in'];
        Mail::send('emails.reminders.basic_reminder',
            ['body' => 'Daily Ops Monitoring']
            , function ($message) use ($file, $mail_ids, $date) {
                $message->to(['ops.monitoring@creditfair.in'])->subject('Daily Ops Monitoring '.$date);
                $message->attachData(file_get_contents(storage_path() . '/app/' . $file), $file);
            });

        unlink(storage_path() . '/app/' . $file);
    }
    CampaignsJobProvider::where('from', 'dailyExcelMailToOPs')->update(['is_available' => 0, 'available_at' => Carbon::tomorrow()->startOfDay()->addHours(8)->toDateTimeString()]);
    }

    public function requestKarzaKYC($id, $ret = 'res'){
        try {
            $application = ConsumerApplication::with(['application_element', 'proFormaInvoice'])
                ->where('id', $id)
                ->first();

            if (!$application->dob) {
                return $this->sendKarzaResponse('FAIL', 'Date of birth required', [], $ret);
            }
            if (!$application->gender) {
                return $this->sendKarzaResponse('FAIL', 'Gender is required', [], $ret);
            }
            if (empty($application->application_element->father_name)) {
                return $this->sendKarzaResponse('FAIL', 'Father Name is required', [], $ret);
            }

            $currentAddress = $this->buildAddress($application, 'current_address');
            if (empty($currentAddress)) {
                return $this->sendKarzaResponse('FAIL', 'Current Address Required', [], $ret);
            }

            $permanentAddress = $this->buildAddress($application, 'permanent_address');
            if (empty($permanentAddress)) {
                return $this->sendKarzaResponse('FAIL', 'Permanent Address Required', [], $ret);
            }

            $application->currentAddress = $currentAddress;
            $application->permanentAddress = $permanentAddress;

            if (empty($application->proFormaInvoice->loan_application_no)) {
                return $this->sendKarzaResponse('FAIL', 'Loan id is required', [], $ret);
            }

            if ($application->co_applicant_name) {
                if (!$application->co_applicant_dob) {
                    return $this->sendKarzaResponse('FAIL', 'Co-Applicant Date of birth required', [], $ret);
                }
                if (!$application->co_applicant_gender) {
                    return $this->sendKarzaResponse('FAIL', 'Co-Applicant Gender is required', [], $ret);
                }
                if (empty($application->application_element->co_applicant_father_name)) {
                    return $this->sendKarzaResponse('FAIL', 'Co-Applicant Father Name is required', [], $ret); // Fixed typo in original "Co-ApplicantFather"
                }

                $coAddress = $this->buildAddress($application, 'co_applicant_address');
                if (empty($coAddress)) {
                    return $this->sendKarzaResponse('FAIL', 'Current Address Required', [], $ret);
                }

                $application->co_applicant_currentAddress = $coAddress;
                $application->co_applicant_permanentAddress = $coAddress; 
            }

            $karzaVideo = new KarzaVideo(new Request(['application' => $application]));
            $data = $karzaVideo->getRequestedAttributes();

            return $this->sendKarzaResponse('OK', null, $data, $ret);

        } catch (\Exception $e) {
            return $this->sendKarzaResponse('FAIL', 'Exception occurred while requesting Karza KYC', [], $ret);
        }
    }

    private function buildAddress($model, $prefix){
        $parts = [
            $model->{$prefix . '_line_1'} ?? '',
            $model->{$prefix . '_state'} ?? '',
            $model->{$prefix . '_city'} ?? '',
            $model->{$prefix . '_pincode'} ?? '',
            $model->{$prefix . '_landmark'} ?? ''
        ];

        return trim(implode(' ', array_filter($parts, function($value) {
            return !empty($value);
        })));
    }

    private function sendKarzaResponse($status, $message, $data, $ret){
        $response = ['status' => $status];

        if (!empty($message)) {
            $response['message'] = $message;
        }

        if (!empty($data)) {
            $response = array_merge($response, $data);
        }

        if ($ret === 'res') {
            return \response()->json($response, 200);
        }

        return $response;
    }

    public function getSalesMISReport(Request $request){
        $from_date = $request->from_date ? $request->from_date : Carbon::now()->startOfMonth()->toDateString();
        $to_date = $request->to_date ? $request->to_date : Carbon::now()->toDateString();

        if($request->export){
            $ratingData = \DB::select('SELECT consumer_application.id as id,whatsapp_customer_service.application_id as application_id,consumer_application.name as "name",whatsapp_customer_service.payload as rating,whatsapp_customer_service.created_at as created_at from whatsapp_customer_service
            LEFT join consumer_application on whatsapp_customer_service.application_id = consumer_application.id where consumer_application.created_at BETWEEN "'.$from_date.' 00:00:00" and "'.$to_date.' 23:59:59" and consumer_application.is_deleted is null');
            $abortData = \DB::select("select merchant.merchant_name as merchant_name,
            merchant_category.name as category,
            consumer_application.id as id,
            consumer_application.name as name,
            consumer_application.state as status,
            consumer_application.loan_amount as loan_amount,
            (select created_at from status_logs where status_logs.status = 'form_completed' and status_logs.application_id = consumer_application.id limit 1) as 'login_date',
            (select created_at from status_logs where status_logs.status = 'approved' and status_logs.application_id = consumer_application.id limit 1) as 'approved_date',
            (select created_at from status_logs where status_logs.status = 'aborted' and status_logs.application_id = consumer_application.id limit 1) as 'abort_date',
            (select reason from status_logs where status_logs.status = 'aborted' and status_logs.application_id = consumer_application.id limit 1) as 'abort_reason'
            from consumer_application
            left JOIN merchant on merchant.id = consumer_application.merchant_id
            LEFT JOIN merchant_category on merchant_category.id = merchant.category_id
            where merchant.is_guest_active = 1 and consumer_application.created_at >= '".$from_date." 00:00:00' and consumer_application.created_at <= '".$to_date." 23:59:59' and consumer_application.is_deleted is NULL");
            $appFlowData = \DB::select('select consumer_application.id,
            consumer_application.name,
            merchant.merchant_name,
            (select created_at from status_logs where (status_logs.status = "Form Completed" or status_logs.status = "In-process" ) and status_logs.application_id = consumer_application.id LIMIT 1) as "Login Date",
            (select created_at from status_logs where status_logs.status = "disbursed" and status_logs.application_id = consumer_application.id LIMIT 1) as "Disbursement Date",
            consumer_application.loan_amount,
            consumer_application.approved_amount,
            consumer_application.state as Status
            from consumer_application 
            left JOIN merchant on merchant.id = consumer_application.merchant_id LEFT JOIN merchant_category on merchant_category.id = merchant.category_id
            left join lenders on lenders.id = consumer_application.lender_id
            left JOIN users on users.id = consumer_application.created_by
            left join emi_calculation on emi_calculation.application_id = consumer_application.id
            left JOIN merchant_offers on merchant_offers.id = emi_calculation.offer_id
            left join consumer_application_element on consumer_application_element.application_id = consumer_application.id
            left join merchant_location on merchant_location.id = consumer_application_element.center_id
                                    left JOIN credit_report on credit_report.application_id = consumer_application.id
            where consumer_application.is_deleted is NULL and consumer_application.created_at >= "'.$from_date.' 00:00:00" and
            consumer_application.created_at <= "'.$to_date.' 23:59:59" group by consumer_application.id');
            $weeklyTatData1 = \DB::select('select consumer_application.id as id,
            consumer_application.name as name,
            merchant.merchant_name as merchant_name,
            merchant_category.name as category,
            consumer_application.created_by as created_by,
            users.name as advisor_name,
            consumer_application.created_at as created_at 
            from consumer_application left JOIN merchant on merchant.id = consumer_application.merchant_id 
            LEFT JOIN merchant_category on merchant_category.id = merchant.category_id
            left join users on users.id = consumer_application.created_by 
            where consumer_application.is_deleted is NULL AND consumer_application.created_at > "'.$from_date.'" 
            order by merchant.merchant_name, consumer_application.created_at');
            $weeklyTatData2 = \DB::select('SELECT status_logs.id, 
            status_logs.application_id, 
            status_logs.user_id, 
            users.name,
            status_logs.status, 
            status_logs.deleted_at, 
            status_logs.created_at, 
            status_logs.updated_at, 
            status_logs.reason
            FROM cfwebbeta.status_logs
            left join users on users.id = status_logs.user_id 
            where status_logs.deleted_at is null and status_logs.created_at > "'.$from_date.'"
            order by application_id ASC, status_logs.created_at');
            $regionWiseDisbursementData = \DB::select("SELECT consumer_application.lender_id as 'lender id',
            consumer_application.id as 'id',
                   consumer_application.name as 'name',
                   consumer_application.loan_amount 'loan amount',
                   consumer_application.approved_amount as 'approved amount',
                   consumer_application.approved_amount * (emi_calculation.subvention/100) as 'Subvention amount',
                   emi_calculation.upfront_from_customer as 'upfront from customer',
                   consumer_application.mobile_number as 'mobile number',
                   merchant.merchant_name as 'merchant name',
                   merchant_category.name as 'category name',
                   (select created_at from status_logs where status_logs.status = 'form completed' and status_logs.application_id = consumer_application.id ORDER by created_at desc LIMIT 1) as 'Login Date',
                   (select created_at from status_logs where status_logs.status = 'disbursed' and status_logs.application_id = consumer_application.id ORDER by created_at desc LIMIT 1) as 'Disbursement Date',
                   consumer_application.state as 'state',
                   users.name as advisor
            FROM consumer_application
                   left JOIN users on users.id = consumer_application.created_by    
                   left JOIN emi_calculation on emi_calculation.application_id = consumer_application.id
                   left Join disbursements on disbursements.disbursed = consumer_application.id
                   left join merchant on merchant.id = consumer_application.merchant_id
                   left join merchant_category on merchant_category.id = merchant.category_id
                   left join status_logs on status_logs.application_id = consumer_application.id
            WHERE consumer_application.state IN ('Ready for disbursement','Disbursed','nach registered','closed','cancelled')
              and status_logs.status = 'Disbursed' and consumer_application.is_deleted is NULL and status_logs.created_at >= '".$from_date." 00:00:00' and status_logs.created_at <= '".$to_date." 23:59:59'");

            if($ratingData || $abortData || $appFlowData || $weeklyTatData1 || $weeklyTatData2 || $regionWiseDisbursementData){
                $jobs = new CampaignsJobProvider();
                $jobs->from = 'salesMISReport';
                $jobs->payload = json_encode(['email' => Auth::user()->email, 'from_date' => $from_date, 'to_date' => $to_date]);
                $jobs->available_at = Carbon::now()->toDateTimeString();
                $jobs->application_id = 181;
                $jobs->created_at = Carbon::now()->toDateTimeString();
                $jobs->is_available = 0;
                $jobs->save();

                \Session::flash('success', 'Data will be received on your email');
            }else{
                \Session::flash('error', 'No data found in selected period');
            }
        }

        return view('admin.reports.sales_mis', ['from_date' => $from_date, 'to_date' => $to_date]);
    }

    public function salesMisReport(Request $request){
        $from_date = $request->get('from_date') ? $request->get('from_date') : Carbon::now()->startOfMonth()->toDateString();
        $to_date = $request->get('to_date') ? $request->get('to_date') : Carbon::now()->toDateString();

        $ratingData = \DB::select('SELECT consumer_application.id as id,whatsapp_customer_service.application_id as application_id,consumer_application.name as "name",whatsapp_customer_service.payload as rating,whatsapp_customer_service.created_at as created_at from whatsapp_customer_service
            LEFT join consumer_application on whatsapp_customer_service.application_id = consumer_application.id where consumer_application.created_at BETWEEN "'.$from_date.' 00:00:00" and "'.$to_date.' 23:59:59" and consumer_application.is_deleted is null');
            $abortData = \DB::select("select merchant.merchant_name as merchant_name,
            merchant_category.name as category,
            consumer_application.id as id,
            consumer_application.name as name,
            consumer_application.state as status,
            consumer_application.loan_amount as loan_amount,
            (select created_at from status_logs where status_logs.status = 'form completed' and status_logs.application_id = consumer_application.id limit 1) as 'login_date',
            (select created_at from status_logs where status_logs.status = 'approved' and status_logs.application_id = consumer_application.id limit 1) as 'approved_date',
            (select created_at from status_logs where status_logs.status = 'aborted' and status_logs.application_id = consumer_application.id limit 1) as 'abort_date',
            (select reason from status_logs where status_logs.status = 'aborted' and status_logs.application_id = consumer_application.id limit 1) as 'abort_reason'
            from consumer_application
            left JOIN merchant on merchant.id = consumer_application.merchant_id
            LEFT JOIN merchant_category on merchant_category.id = merchant.category_id
            where merchant.is_guest_active = 1 and consumer_application.created_at >= '".$from_date." 00:00:00' and consumer_application.created_at <= '".$to_date." 23:59:59' and consumer_application.is_deleted is NULL");
            $appFlowData = \DB::select('select consumer_application.id,
            consumer_application.name,
            merchant.merchant_name,
            (select created_at from status_logs where (status_logs.status = "Form Completed" or status_logs.status = "In-process" ) and status_logs.application_id = consumer_application.id LIMIT 1) as "login_date",
            (select created_at from status_logs where status_logs.status = "disbursed" and status_logs.application_id = consumer_application.id LIMIT 1) as "dibsursement_date",
            consumer_application.loan_amount,
            consumer_application.approved_amount,
            consumer_application.state as status
            from consumer_application 
            left JOIN merchant on merchant.id = consumer_application.merchant_id LEFT JOIN merchant_category on merchant_category.id = merchant.category_id
            left join lenders on lenders.id = consumer_application.lender_id
            left JOIN users on users.id = consumer_application.created_by
            left join emi_calculation on emi_calculation.application_id = consumer_application.id
            left JOIN merchant_offers on merchant_offers.id = emi_calculation.offer_id
            left join consumer_application_element on consumer_application_element.application_id = consumer_application.id
            left join merchant_location on merchant_location.id = consumer_application_element.center_id
                                    left JOIN credit_report on credit_report.application_id = consumer_application.id
            where consumer_application.is_deleted is NULL and consumer_application.created_at >= "'.$from_date.' 00:00:00" and
            consumer_application.created_at <= "'.$to_date.' 23:59:59" group by consumer_application.id');
            $weeklyTatData1 = \DB::select('select consumer_application.id as id,
            consumer_application.name as name,
            merchant.merchant_name as merchant_name,
            merchant_category.name as category,
            consumer_application.created_by as created_by,
            users.name as advisor_name,
            consumer_application.created_at as created_at 
            from consumer_application left JOIN merchant on merchant.id = consumer_application.merchant_id 
            LEFT JOIN merchant_category on merchant_category.id = merchant.category_id
            left join users on users.id = consumer_application.created_by 
            where consumer_application.is_deleted is NULL AND consumer_application.created_at > "'.$from_date.'" 
            order by merchant.merchant_name, consumer_application.created_at');
            $weeklyTatData2 = \DB::select('SELECT status_logs.id, 
            status_logs.application_id, 
            status_logs.user_id, 
            users.name,
            status_logs.status, 
            status_logs.deleted_at, 
            status_logs.created_at, 
            status_logs.updated_at, 
            status_logs.reason
            FROM cfwebbeta.status_logs
            left join users on users.id = status_logs.user_id 
            where status_logs.deleted_at is null and status_logs.created_at > "'.$from_date.'"
            order by application_id ASC, status_logs.created_at');
            $regionWiseDisbursementData = \DB::select("SELECT consumer_application.lender_id as 'lender id',
            consumer_application.id as 'id',
            consumer_application.lender_id,
                   consumer_application.name as 'name',
                   consumer_application.loan_amount 'loan_amount',
                   consumer_application.approved_amount as 'approved_amount',
                   consumer_application.approved_amount * (emi_calculation.subvention/100) as 'subvention_amount',
                   emi_calculation.upfront_from_customer as 'upfront_from_customer',
                   consumer_application.mobile_number as 'mobile_number',
                   merchant.merchant_name as 'merchant_name',
                   merchant_category.name as 'category_name',
                   (select created_at from status_logs where status_logs.status = 'form completed' and status_logs.application_id = consumer_application.id ORDER by created_at desc LIMIT 1) as 'login_date',
                   (select created_at from status_logs where status_logs.status = 'disbursed' and status_logs.application_id = consumer_application.id ORDER by created_at desc LIMIT 1) as 'disbursement_date',
                   consumer_application.state as 'state',
                   users.name as advisor
            FROM consumer_application
                   left JOIN users on users.id = consumer_application.created_by    
                   left JOIN emi_calculation on emi_calculation.application_id = consumer_application.id
                   left Join disbursements on disbursements.disbursed = consumer_application.id
                   left join merchant on merchant.id = consumer_application.merchant_id
                   left join merchant_category on merchant_category.id = merchant.category_id
                   left join status_logs on status_logs.application_id = consumer_application.id
            WHERE consumer_application.state IN ('Ready for disbursement','Disbursed','nach registered','closed','cancelled')
              and status_logs.status = 'Disbursed' and consumer_application.is_deleted is NULL and status_logs.created_at >= '".$from_date." 00:00:00' and status_logs.created_at <= '".$to_date." 23:59:59'");

            $response1[] = ['Id','Name', 'Merchant Name', 'Category','Status','Loan Amount','Login Date','Approved Date','Abort Date','Abort Reason'];

            if($abortData){
                foreach($abortData as $k=>$ad){
                    $data1[] = [
                        'Id' => $ad->id,
                        'Name' => $ad->name,
                        'Merchant Name' => $ad->merchant_name,
                        'Category' => $ad->category,
                        'Status' => $ad->status,
                        'Loan Amount' => $ad->loan_amount,
                        'Login Date' => $ad->login_date,
                        'Approved Date' => $ad->approved_date,
                        'Abort Date' => $ad->abort_date,
                        'Abort Reason' => $ad->abort_reason
                    ];
                }
                $response1[] = $data1;
            }

            $response2[] = ['Id','Name', 'Merchant Name', 'Status', 'Loan Amount','Login Date','Approved Date','Disbursement Date'];

            if($appFlowData){
                foreach($appFlowData as $k=>$afd){
                    $data2[] = [
                        'Id' => $afd->id,
                        'Name' => $afd->name,
                        'Merchant Name' => $afd->merchant_name,
                        'Status' => $afd->status,
                        'Loan Amount' => $afd->loan_amount,
                        'Login Date' => $afd->login_date,
                        'Approved Amount' => $afd->approved_amount,
                        'Disbursement Date' => $afd->dibsursement_date
                    ];
                }
                $response2[] = $data2;
            }

            $response3[] = ['Id','Name', 'Merchant Name', 'Category','Advisor Id','Advisor Name','Created At'];

            if($weeklyTatData1){
                foreach($weeklyTatData1 as $k=>$wtd1){
                    $data3[] = [
                        'Id' => $wtd1->id,
                        'Name' => $wtd1->name,
                        'Merchant Name' => $wtd1->merchant_name,
                        'Category' => $wtd1->category,
                        'Advisor Id' => $wtd1->created_by,
                        'Advisor Name' => $wtd1->advisor_name,
                        'Created At' => $wtd1->created_at
                    ];
                }
                $response3[] = $data3;
            }

            $response4[] = ['Id','Application Id', 'Advisor Id', 'Name','Status','Deleted At','Created At','Reason'];

            if($weeklyTatData2){
                foreach($weeklyTatData2 as $k=>$wtd2){
                    $data4[] = [
                        'Id' => $wtd2->id,
                        'Application Id' => $wtd2->application_id,
                        'Advisor Id' => $wtd2->user_id,
                        'Name' => $wtd2->name,
                        'Status' => $wtd2->status,
                        'Deleted At' => $wtd2->deleted_at,
                        'Created At' => $wtd2->created_at,
                        'Reason' => $wtd2->reason
                    ];
                }
                $response4[] = $data4;
            }

            $response5[] = ['Id','Lender Id','Name','Loan Amount','Approved Amount','Subvention Amount','Upfront From Customer','Mobile Number','Merchant Name','Category Name','Login Date','Disbursement Date','State','Advisor'];

            if($regionWiseDisbursementData){
                foreach($regionWiseDisbursementData as $k=>$rwdd){
                    $data5[] = [
                        'Id' => $rwdd->id,
                        'Lender Id' => $rwdd->lender_id,
                        'Name' => $rwdd->name,
                        'Loan Amount' => $rwdd->loan_amount,
                        'Approved Amount' => $rwdd->approved_amount,
                        'Subvention Amount' => $rwdd->subvention_amount,
                        'Upfront From Customer' => $rwdd->upfront_from_customer,
                        'Mobile Number' => wall_decrypt($rwdd->mobile_number),
                        'Merchant Name' => $rwdd->merchant_name,
                        'Category Name' => $rwdd->category_name,
                        'Login Date' => $rwdd->login_date,
                        'Disbursement Date' => $rwdd->disbursement_date,
                        'State' => $rwdd->state,
                        'Advisor' => $rwdd->advisor
                    ];
                }
                $response5[] = $data5;
            }

            $response6[] = ['Id','Application Id','Name','Rating','Created At'];

            if($ratingData){
                $ratingDataIds = [];
                foreach($ratingData as $k=>$rd) {

                    if (!in_array($rd->application_id, $ratingDataIds)) {
                        $ratingDataIds[] = $rd->application_id;
                        $data6[] = [
                            'Id' => $rd->application_id,
                            'Application Id' => $rd->application_id,
                            'Name' => $rd->name,
                            'Rating' => $rd->rating,
                            'Created At' => $rd->created_at
                        ];
                    }
                }
                $response6[] = $data6 ?? [];
            }

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

            $request = new Request([
                'sheet' => ['App flow Data','Abort Data','Ratings Data','Weekly TAT 1','Weekly TAT 2','Region-wise Net Disbursement Data'],
                'data'  => [$response2, $response1, $response6, $response3, $response4, $response5]
            ]);

            $file = time().'_sales_mis.xlsx';
            Excel::store(new ExporterMultipleSheet($request), $file);

            if($email) {
                Mail::send('emails.reminders.basic_reminder',
                    ['body' => 'Sales MIS reports as requested']
                    , function ($message) use ($file, $email) {
                        $message->to([$email])->subject('Sales MIS Report');
                        // $message->cc([$user->email]);
                        $message->attachData(file_get_contents(storage_path() . '/app/' . $file), $file);
                    });
            }
            unlink(storage_path() . '/app/' . $file);
    }

    private function reviseDocsOnAdvanceReceiptUpload($application_id)
    {
        $application = ConsumerApplication::with('activeOffer')
            ->where('id', $application_id)
            ->first(['id', 'state', 'merchant_id']);

        if (!$application || $application->state !== 'ready for disbursement') {
            return;
        }

        $merchantId = $application->merchant_id ?? null;
        $subventionTypeId = isset($application->activeOffer) ? $application->activeOffer->subvention_type_id : null;
        $emiCalculation = new \App\Http\Controllers\Admin\EMICalculation(new Request());
        $reviseDocumentNeeded = $emiCalculation->updateEMIDate($application_id, $subventionTypeId, $merchantId);
    
        if ($reviseDocumentNeeded) {
            $payload = [
                "cam" => "1", "proforma" => "1", "sanction" => 1, "loanagreement" => 0, "emi_schedule" => 1, "payment_links" => 0
            ];
            $request = new Request();
            $request->merge([
                'id' => $application_id,
                'data' => $payload
            ]);
            $this->reviseDocuments($request);
            $rfdComment = new \App\Comments();
            $rfdComment->application_id = $application_id;
            $rfdComment->user_id = \Auth::check() ? \Auth::user()->id : 107;
            $rfdComment->comment = 'Docs will be revised since advance receipt is uploaded at RFD stage';
            $rfdComment->show_merchant = 0;
            $rfdComment->show_consumer = 0;
            $rfdComment->save();
        }
    }

    public function reviseDocuments(Request $r){
        try{
        if($r->has('data')){
            $log = [
                'application_id' => $r->get('id'),
                'doc_list' => json_encode($r->get('data')),
                'user_id' => isset(Auth::user()->id) ? Auth::user()->id : 107,
                'created_at' => Carbon::now()->toDateTimeString()
            ];
            \App\ReviseDocumentLogs::insert($log);

            $doc = $r->get('data');
            $payload = [
                'payload' => json_encode(['list' => $doc,'auth_user_id' => isset(Auth::user()->id) ? Auth::user()->id : 107, 'app_id' => $r->get('id')]),
                'from' => 'reviseDocuments',
                'application_id' => $r->get('id'),
                'available_at' => Carbon::now()->toDateTimeString(),
                'created_at' => Carbon::now()->toDateTimeString()
            ];
            JobProvider::insert($payload);

            $data = array();
            $data['status'] = 'OK';
            $data['message'] = 'Requested documents will be revised shortly';
            return $data;
        }

        $reviseDocNames = $r->get('list');
        $application_id = $r->get('app_id');
        $appData = ConsumerApplication::with('emi','category', 'merchant','activeOffer', 'application_element', 'proFormaInvoice')->where('id', $application_id)->first(['id', 'lender_id','user_id','merchant_id','state', 'name', 'mobile_number', 'email', 'approved_amount', 'loan_amount','pan_card','aadhaar_card','co_applicant_pan_card','co_applicant_aadhaar_card','merchant_id','co_applicant_mobile_number','co_applicant_name','co_applicant_email','applicant_id','offer_id','purpose']);
        
        if($reviseDocNames->emi_schedule){
            $cwFactory = new CloudWatchLoggerFactory();
            $cwFactory->logger(json_encode(['title' => 'Revise EMI generate', 'application_id' => $application_id, 'loan_amount' => $appData->approved_amount, 'emi_date' => $appData->emi->emi_date, 'interest_type_id' => $appData->activeOffer->interest_type_id, 'merchant_offer_id' => $appData->offer_id]));
            $request = new Request();
            $request->request->add([
                'first_emi_date' => $appData->emi->emi_date,
                'loan_amount' => $appData->approved_amount,
                'merchant_id' => $appData->merchant_id,
                'category_id' => $appData->category->id,
                'interest_type_id' => $appData->activeOffer->interest_type_id,
                'merchant_offer_id' => $appData->offer_id,
                'user_id' => $r->get('auth_user_id')
            ]);
            $approvedLog = StatusLogs::where('application_id', $appData->id)->where('status', 'approved')->orderBy('created_at', 'asc')->first(['created_at']);
            $approvedDate = $approvedLog ? Carbon::parse($approvedLog->created_at) : null;
            $total_insurance = $this->insuranceCalculation($appData->approved_amount, $appData->application_element->discount_by_cf, $appData->emi->processing_fee,0, $appData->proFormaInvoice->insurance_coverage, $approvedDate, $appData->application_element->inverter_gross_project_amount ?? 0);
            ProFormaInvoice::where('application_id', $application_id)->update(['insurance_premium_amount' => $total_insurance]);
            $this->generateEMI($request, $appData, $application_id);
        }
        
        if (isset($reviseDocNames->webhook) && $reviseDocNames->webhook) {
            $payload = $this->getMConnectPayload($application_id, 'approved');
            $result = $this->webhook($application_id, [
                    'merchant_id' => $appData->merchant_id,
                    'type' => 'Application-Webhook',
                    'status' => 'approved',
                    'data' => $payload
                ]);
        }

        $emiValues = DB::selectOne("SELECT processing_fee, legal_charges from emi_calculation where application_id = $application_id");
        if (isset($reviseDocNames->payment_links) && $reviseDocNames->payment_links) {
            $riskController = new RiskController(new Request());
            $rbpAmount = $riskController->getRiskBasedPFCalculation($application_id, $emiValues->processing_fee);
            if ($rbpAmount < 0) {
                $newPF = $emiValues->processing_fee + (-$rbpAmount);
                $riskController->resetRiskBasedPFOnOfferChange($application_id, $newPF);
            } else {
                $riskController->updateDetailsOnReviseDocuments($application_id);
            }
            $result_arr = [
                'processing_fee' => ['amount' => '', 'link' => '']
            ];
            $request = new Request();
            $frntcntrller = new FrontController();
            $result = $frntcntrller->getFeesData($appData->id);
            if (isset($result['payment_details']['Total Payment']) && isset($result['total_payment_link'])) {
                $request->request->add([
                    'id' => $appData->id,
                    'name' => $appData->name,
                    'mobile' => $appData->mobile_number,
                    'type' => 'total_payment',
                    'amount' => $result['payment_details']['Total Payment']['amount'],
                    'link' => $result['total_payment_link'],
                    'approved_amount' => $appData->approved_amount,
                ]);
                if ($appData->lender_id == 2) {
                    (new ConsumerApplicationController())->sendNewPaymentLink($request);
                }
            }
        }

        // payment entry revise in case amount changes - PF and Legal Charge
        $currentInsurance = $currentProcessingFee = $currentLegalCharges = 0;
        $paymentEntry = PaymentTransaction::where(['application_id' => $application_id, 'mode' => 'Adjusted In disbursement'])->whereNull('deleted_at')->whereNull('is_deleted_at')->get(['amount', 'payment_for']);
        if (isset($paymentEntry)) {
            foreach ($paymentEntry as $entry) {
                if ($entry->payment_for == 'legal_charges') {
                    $currentLegalCharges += $entry->amount;
                }
                if ($entry->payment_for == 'processing_fee') {
                    $currentProcessingFee += $entry->amount;
                }
            }
            if (isset($currentProcessingFee) && $currentProcessingFee != $emiValues->processing_fee) {
                DB::table('payment_transactions')
                    ->where('application_id', $application_id)
                    ->where('mode', 'Adjusted In disbursement')
                    ->where('payment_for', 'processing_fee')
                    ->update(['deleted_at' => Carbon::now()->toDateTimeString(),
                    'is_deleted_at' => Carbon::now()->toDateTimeString(),
                    'deleted_by' => 107]);
            }
            if (isset($currentLegalCharges) && $currentLegalCharges != $emiValues->legal_charges) {
                DB::table('payment_transactions')
                    ->where('application_id', $application_id)
                    ->where('mode', 'Adjusted In disbursement')
                    ->where('payment_for', 'legal_charges')
                    ->update(['deleted_at' => Carbon::now()->toDateTimeString(),
                    'is_deleted_at' => Carbon::now()->toDateTimeString(),
                    'deleted_by' => 107]);
            }
        }

        //Remove insurance if not applicable on lender at the time of lender change
        //    $this->updateInsuranceConfigBasedOnLender($appData);

        if($reviseDocNames->loanagreement){
            $id = $application_id;
            $system = 1;
            $aggrementgenerate = 0;
            $avanseLAdocRevise = false;
            $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;
            }
            $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'] = (new FrontController())->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'] = (new FrontController())->vernaculardeclarationarray[$signed_data[1]['language']];
                    $signed_data[1]['longitude'] = $geolocation[1]['longitude'] ?? '';
                    $signed_data[1]['latitude'] = $geolocation[1]['latitude'] ?? '';
                }

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

                if($signed_data == ""){
                    $signed_data = new DigitalSignDetails();
                }
                $type = "Loan Agreement Esign";

                $isInsuranceTaken = 0;
                $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');
                $save_agreement_document_details = [];
                $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'];
                } 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 == 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 == ConsumerApplication::AVANSE_LENDER_ID ){ // && $consumer_details['approved_amount'] <= 300000
                    $cDocObj =  new ConsumerDocument(new Request([]));
                    $agreement =  $cDocObj->getSanctionLetterAndLoanAgreement($id, $signed_data);
                    (new ConsumerDocument(new Request([])))->uploadToS3(str_replace(' ','_',strtolower($type)), $id, $agreement['pdf']->output());
                    $avanseLAdocRevise = true;
                }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' => 1, 'signed_data' => $signed_data, 'lender' => $viewParameter['lender'], 'combined_sl_la' => $viewParameter['combined_sl_la']];
                    $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' => 1, 'signed_data' => $signed_data, 'lender' => $viewParameter['lender'], 'combined_sl_la' => $viewParameter['combined_sl_la']];
                    $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 == Vivriti::$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']];
                    $pdf->setOption('header-html', (new ConsumerDocument(new Request()))->getPDFHeaderView());
                    $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 == 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
                    $cDocObj = new ConsumerDocument(new Request([]));
                    $agreement = $cDocObj->getSanctionLetterAndLoanAgreement($id, $signed_data, false, 'admin.documents.blacksoil.sanction_letter', 'admin.documents.blacksoil.loan_agreement_v1');
                    if ($agreement && isset($agreement['pdf'])) {
                        (new ConsumerDocument(new Request([])))->uploadToS3(str_replace(' ','_',strtolower($type)), $id, $agreement['pdf']->output());
                        $avanseLAdocRevise = true;
                    }
                }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');
                    }
                }
                if(!$avanseLAdocRevise){
                    $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'=>$type,'lender'=> $viewParameter['lender']])->render());

                    $file = $pdf;
                    $uploadDoc = new ConsumerDocument(new Request());
                    // if ($isInsuranceTaken) {
                    if(false){
                        /*$consumerDocument = new ConsumerDocument(new Request());
                        $file = $consumerDocument->getInsuranceDocuments($id, $pdf, $viewParameter['user']['insurance_kotak_file']);
                        $file_id = $uploadDoc->uploadToS3(str_replace(' ','_',strtolower($type)), $id, $file);
                        $uploadDoc->saveDocumentDetails($id, $file_id, 'LOAN_AGREEMENT', $save_agreement_document_details);*/
                    }else{
                        $file_id = $uploadDoc->uploadToS3(str_replace(' ','_',strtolower($type)), $id, $file->output());
                        $uploadDoc->saveDocumentDetails($id, $file_id, 'LOAN_AGREEMENT', $save_agreement_document_details);
                    }
                }
            }
        }

        if($reviseDocNames->cam){
            (new ConsumerApplicationController())->generateCAMReport($application_id,false);
        }

        $consumer_application_elements = ConsumerApplicationElement::with('application')->where('application_id', $application_id)->first();
        $lender = Lenders::where('id',$consumer_application_elements->application->lender_id)->first();

        if($reviseDocNames->proforma){
            $this->sendProForma($application_id);
        }

        if($reviseDocNames->sanction){
            $request = new Request();
            $request->request->add([
                'type' => 'Sanction Letter',
                'bot' => true,
                // 'test_bot' => false,
                // 'from_mail' => _env('CENTRALOPS')
            ]);

            $document = (new ConsumerDocument($request));
            $documentDetails = $document->getDocument($application_id);
            $documentDetails['pdf'] = 1;

            if (!empty($documentDetails['lender']) && $documentDetails['lender']['id'] == ConsumerApplication::AVANSE_LENDER_ID) { // Avanse is lender
                $sanction_letter_view = 'admin.documents.avanse.sanction_letter_v3';
            } elseif (!empty($documentDetails['lender']) && $documentDetails['lender']['id'] == JMServices::$lender_id) {
                $sanction_letter_view = 'admin.documents.jm.sanction_letter';
            } elseif (!empty($documentDetails['lender']) && $documentDetails['lender']['id'] == Vivriti::$lender_id) {
                $sanction_letter_view = 'admin.documents.vivriti.sanctionLetter_v_four';
            } elseif (!empty($documentDetails['lender']) && $documentDetails['lender']['id'] == Services::$lender_id) { // ABFL is lender
                $sanction_letter_view = 'admin.documents.abfl.sanction_letter';
            } elseif (!empty($documentDetails['lender']) && $documentDetails['lender']['id'] == \App\BlackSoil::$lender_id) { // BlackSoil is lender
                $sanction_letter_view = 'admin.documents.blacksoil.sanction_letter';
            } elseif (!empty($documentDetails['lender']) && $documentDetails['lender']['id'] == KMGP2P::$lender_id) { // KMGP2P is lender
                $sanction_letter_view = 'admin.documents.kmgp2p.sanction_letter_kmgp2p';
            } else {
                if ($consumer_application_elements->agreement_version == 2) {
                    $sanction_letter_view = 'admin.documents.sanctionLetter_v_four';
                } else {
                    $sanction_letter_view = 'admin.documents.sanctionLetter';
                }
            }

            $data = [
                'txt' => view($sanction_letter_view, $documentDetails),
            ];
            $pdf = App::make('snappy.pdf.wrapper');
            $pdf->loadHTML($data['txt'])->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);
            $doc_File = $pdf->setOption('footer-html', view('admin.editor.footer', ['type' => $request->get('type'), 'lender' => $lender])->render());
            $fileID = $document->uploadToS3(str_replace(' ', '_', strtolower($request->get('type'))), $application_id, $doc_File->output());
            $document->saveDocumentDetails($application_id, $fileID, 'SANCTION_LETTER', $documentDetails);
        }
        }catch(\Exception $e){
            // (new \App\Slack(new Request(['title' => 'Revise Failure', 'fields' => ['error' => $e->getMessage(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString(), 'application_id' => $application_id], 'group' => Slack::$STAGE_TESTING])))->send();
            $cwFactory = new CloudWatchLoggerFactory();
            $cwFactory->logger(json_encode(['title' => 'Revise Failure', 'error' => $e->getMessage(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString(), 'application_id' => $application_id]));
        }
        return true;
    }

    public function generateSoftBureauReport($id,$type = 'customer', $applicantType = 1 , $runBre = true){
        (new Slack(new Request(['title' => 'Soft Bureau PUll Method Execution Start', 'fields' => ['id' => $id, 'type' => $type, 'applicantType' => $applicantType, 'runBre' => $runBre], 'group' => Slack::$STAGE_TESTING])))->send();
        $customer = ConsumerApplication::with('creditReport', 'merchant')->where('id',$id)->first(['id','merchant_id','name','mobile_number','pan_card','co_applicant_name','co_applicant_mobile_number','co_applicant_pan_card', 'purpose']);

        $applicant_type = Input::has('applicant_type') ? Input::get('applicant_type') : $applicantType;

        (new Slack(new Request(['title' => 'Soft Bureau PUll Method Execution Start', 'fields' => ['id' => $id, 'type' => $type, 'applicantType' => $applicantType, 'runBre' => $runBre], 'group' => Slack::$STAGE_TESTING])))->send();

        $consent_type = ($applicant_type == 1) ? "consent_logs" : "co_app_consent_logs";
        $consent_flag = ($applicant_type == 1) ? "is_consent" : "is_co_app_consent";

        $consumerFiles = ConsumerApplicationFiles::where([
            ['consumer_application_id', $id],
            ['file_type', $consent_type],
            ['applicant_type', $applicant_type]
        ])->first();

        $applicationElement = ConsumerApplicationElement::where('application_id', $id)->first([$consent_flag]);

        // Allow pull when consent log exists OR flag is set (mconnect may set the flag before the consent PDF job finishes).
        $consentReceived = $consumerFiles
            || ($applicationElement && (int) $applicationElement->{$consent_flag} === 1);

        if (!$consentReceived) {
            $consentErr = ((int) $applicant_type === 1)
                ? 'Please get applicant consent.'
                : 'Please get Co-Applicant consent.';
            return response()->json(['status' => 'FAIL', 'message' => $consentErr]);
        }

        $credit_report = CreditReport::where('application_id', $id)
                                                ->where('applicant_type', $applicant_type)
                                                ->whereNull('deleted_at')
                                                ->first(['id']);

        $callFrom = Input::has('call_from')?Input::get('call_from'): '';
        $skip_pan_validation = (bool) (_env('SKIP_PAN_VALIDATION') ?? false);

        if(!isset($credit_report->id)){
            if($applicant_type == 2){
                if(isset($customer->co_applicant_name) && isset($customer->co_applicant_mobile_number)){
                    $bureauData = array(
                        'application_id' => "$customer->id",
                        'applicant_type' => "$applicant_type",
                        'pan_card' => $customer->co_applicant_pan_card ?? '',
                        'request_type' => $type,
                        'first_name' => explode(' ', trim($customer->co_applicant_name))[0],
                        'last_name' => substr(rtrim($customer->co_applicant_name), strrpos(rtrim($customer->co_applicant_name), ' ') + 1),
                        'mobile_number' => $customer->co_applicant_mobile_number,
                        'document_type' => 'PAN_DETAILED',
                        'vendor' => 'admin'
                    );
                }else{
                    return response()->json(['status'=>'FAIL','message'=>'Either co application name or co applicant mobile number is missing']);
                }
            }else{
                if(isset($customer->name) && isset($customer->mobile_number)){
                    $bureauData = array(
                        'application_id' => "$customer->id",
                        'applicant_type' => "$applicant_type",
                        'request_type' => $type,
                        'pan_card' => $customer->pan_card ?? '',
                        'first_name' => explode(' ', trim($customer->name))[0],
                        'last_name' => substr(rtrim($customer->name), strrpos(rtrim($customer->name), ' ') + 1),
                        'mobile_number' => $customer->mobile_number,
                        'document_type' => 'PAN_DETAILED',
                        'vendor' => 'admin',
                        'skip_pan_validation' => $skip_pan_validation
                    );
                }else{
                    return response()->json(['status'=>'FAIL','message'=>'Either application name or mobile number is missing']);
                }
            }
            // $bureauData = array(
            //     'application_id' => '2510',
            //     'applicant_type' => '1',
            //     'request_type' => 'customer',
            //     'first_name' => 'Ganesh',
            //     'last_name' => 'Misri',
            //     'mobile_number' => '9674006122',
            //     'vendor' => 'admin'
            // );

            $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => _env('EXPERIAN_SOFT_PULL_HOST'),
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => "",
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => "POST",
                CURLOPT_POSTFIELDS => json_encode($bureauData),
                CURLOPT_HTTPHEADER => array(
                    "Content-Type: application/json",
                    "X-Client-Id: "._env('EXPERIAN_SOFT_PULL_ID'),
                    "X-Client-Secret: "._env('EXPERIAN_SOFT_PULL_SECRET'),
                ),
            ));

            $res = curl_exec($curl);
            $data = json_decode($res, 1);
            $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
            $err = curl_error($curl);
            curl_close($curl);

            $status = 'OK';
            $message = isset($data["message"]) ? $data["message"] : 'Soft Bureau Pulled Successfully';

            (new Slack(new Request(['title' => 'Soft Bureau PUll', 'fields' => ['error' => json_encode($err), 'payload' => json_encode($bureauData), 'response' => json_encode($data)], 'group' => Slack::$STAGE_TESTING])))->send();

            if (empty($res) || is_null($data) || $data === 'null') {
                $status = 'FAIL';
                $message = 'Received empty or invalid response from Experian API';
            }

            if(isset($data['error'])){
                $err = $data['error']['message'] ?? 'Failed to pull bureau';
                $message = $err;
                $status = 'FAIL';
            }else if($err){
                $message = $err;
                $status = 'FAIL';
            }

            if ($err && isset($data['message']) && $data['message'] != 'Bureau Fetched Successfully' && $callFrom == "frontend"){
                $message = $err;
                \Session::flash('error', $message);
                return response()->json(['status'=>'FAIL','message'=>$message]);
            } else if(isset($data['status'])){
                $status = $data['status'];
                $message = $data['message'] ?? $data['error']['message'];
                if($data['status'] == 'FAIL' && $callFrom == "frontend"){
                    \Session::flash('error', $message);
                    // return response()->json(['status'=>'FAIL','message'=>$message]);
                }
            }else if($httpcode != 200){
                $status = 'FAIL';
            }

            if($status == 'FAIL'){
                // autoBRE hard pull only when consent is received for this applicant type
                if ($type == 'autoBRE' && !$consentReceived) {
                    return response()->json(['status' => 'FAIL', 'message' => 'Consent not received from hard pull']);
                }
                Input::merge(['applicant_type' => $applicant_type]);
                if ($this->isEquifaxEnabled) {
                    $eqR = $this->generateEqifaxReport($id);
                    if ($eqR) {
                        $status = isset($eqR['status']) ? $eqR['status'] : 'FAIL';
                        if (isset($eqR['status'], $eqR['message']) && $eqR['status'] === 'FAIL' && strpos($eqR['message'], 'consent missing') !== false) {
                            $eqR['message'] = 'Soft bureau failed system is trying to do hard pull for that Consent is required';
                        }
                    } else {
                        return response()->json(['status' => 'FAIL', 'message' => 'Something went wrong']);
                    }
                }
            }
        }else{
            $status = 'OK';
            $message = 'Bureau Fetched Successfully';
        }
        
        $isApproved = 0;
        $isRejected = 0;
        $isPreApproved = 0;
        if($status == 'OK' && ($message == 'Bureau Fetched Successfully' || (isset($eqR['message']) && ($eqR['message'] == 'Equifax Report Generated Successfully' || $eqR['message'] == 'Experian Report Generated Successfully')))){
            (new Slack(new Request(['title' => 'AutoDecision after bureau pull', 'fields' => ['type' => $type, 'log_decision' => Input::has('log_decision') ? Input::get('log_decision') : ''], 'group' => Slack::$STAGE_TESTING])))->send();
            if(Input::has('log_decision') && Input::get('log_decision') && $type != 'autoBRE'){
                $this->current_status = 'waiting for decision';
                $this->updateStatus($id);
            }
            if ($applicant_type == 2) {
                $grade = new GradeController(new Request());
                $grade->autoApproveInitCoapplicant($id);
            }
            if($runBre && $applicant_type == 1){
                $autoDecisionResult = $this->runAutoDecision($id, $type);
                $isApproved = isset($autoDecisionResult['isApproved']) ? $autoDecisionResult['isApproved'] : 0;
                $isRejected = isset($autoDecisionResult['isRejected']) ? $autoDecisionResult['isRejected'] : 0;
                $isPreApproved = isset($autoDecisionResult['isPreApproved']) ? $autoDecisionResult['isPreApproved'] : 0;
            }
        }

        return response()->json(['status'=>$status,'message'=>$message, 'is_approved' => $isApproved, 'is_rejected' => $isRejected, 'is_pre_approved' => $isPreApproved]);
    }

    public function sendWarningEmailForDisbursement(Request $request){
        try{
            $applicationInfo = ConsumerApplication::with('merchant')->where('id',$request->get('app_id'))->first();
            $appLink = \request()->getSchemeAndHttpHost().'/admin/consumer-applications/edit/'.$applicationInfo->id;
            $message = "Hi Team,<br><br>

            This is to inform you that disbursement team has made the case ready for disbursement where merchant status is not ready for disbursement<br>
            
            Merchant Name - ".$applicationInfo->merchant->merchant_name."<br>
            Link of Case - ".$appLink."<br>
            
            Please check and do the needful<br>
            
            Your savior,<br>
            Credit Fair";

            $mail = env('APP_CONNECTION') ? 'bd@creditfair.in' : 'tech@creditfair.in';
            Mail::send('emails.reminders.basic_reminder',
                ['body' => $message]
                , function ($message) use ($mail) {
                    $message->to($mail)->subject('Disbursement happening to Merchant where status is not Ready for Disbursement');
                });

            return response()->json(['status'=>'OK','message'=>'Mail has been sent successfully']);
        }catch(Exception $e){
            return response()->json(['status'=>'FAIL','message'=>'Failed to send mail']);
        }
    }

    public function secondPhaseCommunication(Request $req){
        try{
            $id = $req->get('id');
            $appData = ConsumerApplication::with('merchant')->where('id',$id)->first(['id', 'name', 'mobile_number', 'merchant_id']);

            $csms = 'Dear '.$appData->name.', Congratulations, your 2nd tranche of the loan is disbursed by BlackSoil Capital Private Limited';
            $entity = ['templateid' => '1307168026603891097', 'entityid' => Templates::$entityid];
            send_sms($appData->mobile_number, ['message' => $csms, 'id' => $id, 'id_type' => 'application_id', 'templateDetails' => $entity]);

            if(isset($appData->merchant->contact_number)) {
                $msms = 'Dear ' . $appData->merchant->merchant_name . ', A payment for 2nd Tranche Rs ' . $req->get('amount') . ' on behalf of ' . $appData->name . ' has been sent to your account ending in ' . $req->get('account') . '.  Regards, Team Credit Fair, 919967235047';
                $entity = ['templateid' => '1307168026615493886', 'entityid' => Templates::$entityid];
                send_sms($appData->merchant->contact_number, ['message' => $msms, 'id' => $id, 'id_type' => 'application_id', 'templateDetails' => $entity]);
            }

            return response()->json(['status'=>'OK','message'=>'SMS sent successfully']);
        }catch(Exception $e){
            return response()->json(['status'=>'FAIL','message'=>'Fail to send sms']);
        }
    }

    public function saveFCMToken(Request $request){
        $status = 'FAIL';
        if(Auth::check()){
            $user = Auth::user();
            $GCMRegistraion = GCMRegistraion::where('user_id', $user->id)->where('device_type', 'admin-user')->where('status', 'Inactive')->first(['id']);
            if(!isset($GCMRegistraion->id)){
                GCMRegistraion::insert(
                    [
                        'user_id' => $user->id,
                        'device_type' => 'admin-user',
                        'device_id' => 'admin-user',
                        'status' => 'active',
                        'fcm_id' => $request->get('currentToken'),
                        'created_at' => Carbon::now()->toDateTimeString()
                    ]
                );
                $status = 'OK';
            }else{
                GCMRegistraion::where('id', $GCMRegistraion->id)->update(
                    [
                        'status' => 'active',
                        'fcm_id' => $request->get('currentToken'),
                        'updated_at' => Carbon::now()->toDateTimeString()
                    ]
                );
                $status = 'OK';
            }
        }

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

    public function getOneFinStatus(Request $request){
        $data = (new OneFinService($request))->getStatus();
        $table = '<tr><td>API</td><td>Status</td><td>Message</td></tr>';
        foreach($data as $service => $item){
            $status = $item ? 'Done' : 'Pending';
            if($status == 'Done'){
                $status = $item->status ?? '-';
            }
            $message = $item->message ?? '';
            if($message) {
                $messageObj = json_decode($item->message);
                if ($messageObj) {
                    $message = $messageObj->Message;
                    if($message instanceof \stdClass){

                        $message = $this->getMessageString($message);
                    }
                }
            }
            $table .= '<tr><td>'.$service.'</td><td>'.$status.'</td><td>'.$message.'</td></tr>';
        }
        return \response()->json(['status' => 'OK', 'data' => $table], 200);
    }

    public function getMessageString($message){
        if(isset($message->data->broker_id)){
            return 'BrokerID: <b>'.$message->data->broker_id.'</b>';
        }
        if(isset($message->data->loan_account_number)){
            return 'Loan Account Number: <b>'.$message->data->loan_account_number.'</b>';
        }
        if(isset($message->data->status)){
            return 'Repayment Fetched: <b>'.$message->data->status.'</b>';
        }
        if(isset($message->data->nach_mandate_id)){
            return 'NACH Mandate ID: <b>'.$message->data->nach_mandate_id.'</b>';
        }

        return json_encode($message->data ?? $message->error);
    }

    public function pushToOnefin(Request $request){
        $OneFinService = new OneFinService($request);
        $data = $OneFinService->getStatus();

        $error = 'Successfully pushed the application';
        foreach($data as $service => $item){
            if(!$item || (isset($item->status) && $item->status != 'success')){
                $success = true;
                if($service == 'onBoardChannelEntity'){
                    $success = $OneFinService->onBoardChannelEntity();
                    $data = $success->getData();
                    if($data->status == 'FAIL'){
                        $error = $data->data ?? $data->status;
                        break;
                    }
                    //$OneFinService->updateAPIStatus($service, $success);
                }
                if($success && $service == 'createLoan'){
                    $success = $OneFinService->createLoan();
                    $data = $success->getData();
                    if($data->status == 'FAIL'){
                        $error = $data->data ?? $data->status;
                        break;
                    }
                    //$OneFinService->updateAPIStatus($service, $success);
                }
                if($success && $service == 'postLoanRepayment'){
                    $transaction = PaymentTransaction::where('application_id', $request->get('id'))->where('mode', '!=', 'Adjusted In disbursement')->whereIn('payment_for', ['processing_fee'])->first();
                    if (isset($transaction->id)) {
                        $success = $OneFinService->postLoanRepayment();
                    }else{
                        $OneFinService->updateAPIStatus($service, 'success');
                    }
                    /* $data = $success->getData();
                        if($data->status == 'FAIL'){
                        $error = $data->data ?? $data->status;
                        break;
                    }*/
                    //$OneFinService->updateAPIStatus($service, $success);
                }
                if($success && $service == 'createMandate'){
                    $success = $OneFinService->createMandate();
                    $data = $success->getData();
                    if($data->status == 'FAIL'){
                        $error = $data->data ?? $data->status;
                        break;
                    }
                    //$OneFinService->updateAPIStatus($service, $success);
                }
                if($success && $service == 'loanDisbursal'){
                    $success = $OneFinService->loanDisbursal();
                    $data = $success->getData();
                    if($data->status == 'FAIL'){
                        $error = $data->data ?? $data->status;
                        break;
                    }
                    //$OneFinService->updateAPIStatus($service, $success);
                }
                if($success && $service == 'getRepaymentSchedule'){
                    $success = $OneFinService->getRepaymentSchedule();
                    $data = $success->getData();
                    if($data->status == 'FAIL'){
                        $error = $data->data ?? $data->status;
                        break;
                    }
                    //$OneFinService->updateAPIStatus($service, $success);
                }
            }
        }

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

    public function getPageConfig(Request $request){

        $page_config = PageConfig::where('page', $request->get('page'))->orderBy('created_at', 'desc')->first(['config']);
        if (!isset($page_config->config)) {
            $page_config = new \stdClass();
            $page_config->config = '{
"worker": {
    "identifier_id": "",
"element": {
  "attributes": {
    "id": ""
  },
  "fields": []
}
}
}';
        }
        return response()->json(['status' => 'OK', 'data' => $page_config], 200);
    }

    public function savePageConfig(Request $request){
        $message = 'Failed to updated config';
        $status = 'FAIL';
        if($request->get('page') && $request->get('config')) {
            $_page_config = PageConfig::where('page', $request->get('page'))->first(['id', 'version']);
            $date = Carbon::now()->toDateTimeString();
            $user_id = Auth::user()->id;
            PageConfig::insert([
                'page' => $request->get('page'),
                'config' => $request->get('config'),
                'version' => isset($_page_config->version) ?? ($_page_config->version + 1 ?? 0),
                'created_by' => $user_id,
                'created_at' => $date
            ]);

            if (isset($_page_config->id)) {
                PageConfig::where('id', $_page_config->id)->update(['deleted_at' => $date, 'deleted_by' => $user_id]);
            }

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

    public function oneFinDashboard(Request $request){

        $statusLogs = StatusLogs::whereIn('status', ['disbursed'])->where('created_at', '>=' ,'2024-07-10 00:00:00')->get(['application_id']);
        $include_ids = [];
        foreach($statusLogs as $statusLog){
            $include_ids[] = $statusLog->application_id;
        }
        $applications = ConsumerApplication::whereIn('state',['ready for disbursement', 'disbursed', 'nach registered']);
        if($request->has('id') && $request->get('id')){
            $applications = $applications->where('id', $request->get('id'));
        }
        if($request->has('name') && $request->get('name')){
            $applications = $applications->where('name', $request->get('name'));
        }

        $oneFinService = new OneFinService($request);
        $apiCount = count($oneFinService->apis);
        $query = "SELECT application_id FROM one_fin_migration WHERE status = 'success' GROUP BY application_id HAVING COUNT(*) = ".$apiCount.";";
        $data = DB::select($query);
        $ids = [];
        foreach($data as $item){
            $ids[] = $item->application_id;
        }

        if($include_ids){
            $applications = $applications->whereIn('id', $include_ids);
        }

        if($ids){
            $applications = $applications->whereNotIn('id', $ids);
        }

        $applications = $oneFinService->getConfig($applications);



        $applications = $applications->select('id', 'name')->paginate(10);
        /*foreach($applications as $application){
            $this->pushToOnefin(new Request(['id' => $application->id]));
        }*/

        return view('admin.onefin.index', ['applications' => $applications]);
    }

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

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

    public function updateKMGP2PApplicationStatus(Request $request){
        if ($request->has('application_id')) {
            $appId = $request->get('application_id');
            if($appId){
                $kmgAppln = KMGP2PBorrowerReg::where('kmg_loan_id', $appId)->where('result','success')->first(['application_id']);
                if(isset($kmgAppln->application_id)){
                    ConsumerApplication::whereId($kmgAppln->application_id)->update(['state' => 'disbursement query', 'updated_at' => Carbon::now()->toDateTimeString()]);

                    $statusLog = new StatusLogs();
                    $statusLog->application_id = $kmgAppln->application_id;
                    $statusLog->user_id = (Auth::user()) ? Auth::user()->id : 107;
                    $statusLog->reason = "KMG P2P Application deleted in CFC dashboard";
                    $statusLog->status = "disbursement query";
                    $statusLog->created_at = Carbon::now()->toDateTimeString();
                    $statusLog->save();
                }
            }
        }
    }

    public function checkPermissionGetComments(){
        if(\Illuminate\Support\Facades\Session::has('Confidential_Notes|-64')){
            return true;
        }
        return false;
    }

    public function getPageService(){
        return view('admin.page-service.index');
    }

    public function getMetabaseReports(){
        $METABASE_SITE_URL = _env('METABASE_SITE_URL');
        $METABASE_SECRET_KEY = _env('METABASE_SECRET_KEY');
        $payload = [
              "resource" => ["dashboard" => 34],
              "params" => [
                  'action_date' => 1
              ],
              "exp" => time() + (60 * 10)
        ];
        $token = JWT::encode($payload, $METABASE_SECRET_KEY);
        $iframeUrl = $METABASE_SITE_URL . "/embed/dashboard/" . $token . "#bordered=true&titled=true&filter=true";
        return view('admin.metabase.index', ['iframeUrl' => $iframeUrl]);
    }

    public function saveConsent($application, $applicantType, $action){
        // geo tagging data
        $geoLatitude = $action['latitude'] ?? '';
        $geoLongitude = $action['longitude'] ?? '';
        $geoAddress = '';
        $geoAccuracy = '';
        $kid = 'SA'.$application->id.$applicantType;

        $consentExists = ConsentLog::where('application_id', $application->id)->where('applicant_type', $applicantType)->first(['id']);
        if(!isset($consentExists->id)) {
            $consentLog = new ConsentLog();
            $consentLog->application_id = $application->id;
            $consentLog->ips = (new ApiController())->get_client_ip();
            $consentLog->latitude = $geoLatitude;
            $consentLog->longitude = $geoLongitude;
            $consentLog->status = '1';
            $consentLog->created_at = date('Y-m-d H:i:s');
            $consentLog->updated_at = date('Y-m-d H:i:s');
            $consentLog->type = 'self_attested_kyc';
            $consentLog->applicant_type = $applicantType;
            $consentLog->save();
        }


        ConsumerApplicationElement::where('application_id', $application->id)->update(['is_consent' => 1]);
        ConsentController::removeConsentFromMandatoryList($application->id, $applicantType == 1 ? 'consent_logs' : 'co_app_consent_logs');

        $consumerfiles = ConsumerApplicationFiles::where('consumer_application_id', $application->id)->where('file_type', 'consent_logs')->where('doc_ref_id',$kid)->get();
        if (count($consumerfiles) == 0) {
            $view = view('admin.consumer-application.consent_logs_document_lat_long', ['data' =>
                [
                    'application_id' => $application->id,
                    'name' => $applicantType == 1 ? $application->name : ($applicantType == 2 ? $application->co_applicant_name : ''),
                    'address' => $geoAddress,
                    'mobile' => $applicantType == 1 ? $application->mobile_number : ($applicantType == 2 ? $application->co_applicant_mobile_number : ''),
                    'latitude' => $geoLatitude,
                    'accuracy' => $geoAccuracy,
                    'longitude' => $geoLongitude,
                    'consent_timestamp' => Carbon::now()->toDateTimeString(),
                    'lender_id' => $application->lender_id
                ]
            ]);
            $filePath = '/'.$application->id.'/';
            $applicantTypestr = $applicantType == 2 ? "co_applicant_" : "";

            $pdf = App::make('snappy.pdf.wrapper');
            $pdf->setTimeout(300);
            (new ApiController())->uploadtoS3Digio($filePath.$applicantTypestr.'consent_logs.pdf', $pdf->loadHTML($view)->output(), $applicantTypestr.'consent_logs', $application->id, $applicantType, $kid);
        }
    }

    public function storeLanguage(Request $request)
    {
        // Validate the language input
        $request->validate([
            'language' => 'required|string'
        ]);
        $app_id = isset($request->application_id) ? $request->application_id : '';
        if($app_id != ''){
            $applicationElementObject = ConsumerApplicationElement::where('application_id', $app_id)->first();
            $applicationElementObject->preferred_language = $request->language;
            $applicationElementObject->save();
            // Return a success response
            return response()->json(['success' => true]);
        }
        return response()->json(['success' => false]);
    }

    private function getFilters(Request $request){
        $data['lenders'] = Lenders::orderBy('id','desc')->get(['id', 'name']);
        $data['merchants'] = Merchant::where('is_guest_active', 1)->orderBy('merchant_name', 'asc')->whereNull('deleted_at')->get(['id', 'merchant_name']);
        if (Auth::user()->user_type == UserTypes::$merchant_v2) {
            $data['merchants'] = Merchant::where('id', Auth::user()->merchant_id)->orWhereIn('anchor_merchant_id', [Auth::user()->merchant_id])->orderBy('merchant_name', 'asc')->get(['id', 'merchant_name']);
        }
        $data['combine_merchant'] = [];
        $data['search_text'] = $request->input('search_text');
        $data['search_text_by'] = $request->input('search_text_by');
        $data['from_date'] = ($request->has('from_date') && !empty($request->get('from_date'))) ? Carbon::createFromFormat('Y-m-d', $request->get('from_date'))->toDateString() : '';
        $data['to_date'] = ($request->has('to_date') && !empty($request->get('to_date'))) ? Carbon::createFromFormat('Y-m-d', $request->get('to_date'))->toDateString() : '';
        $data['sort_field'] = ($request->has('sort_field')) ? $request->get('sort_field') : 'updated_at';
        $data['sort_direction'] = ($request->has('sort_direction')) ? $request->get('sort_direction') : 'desc';
        $data['direction_sort'] = ['asc' => 'Ascending','desc' => 'Descending'];
        $data['field_sort'] = ['id' => 'App Id', 'name'=>'Full Name', 'loan_amount'=>'Loan Amount', 'updated_at' => 'Latest Updated', 'created_at'=>'Latest Created'];
        $data['sources'] = ConsumerApplication::where('is_deleted')->groupBy('updated_by')->get(['updated_by as source']);
        $data['users'] = User::where('user_type', '>=', 5)->whereNull('deleted_at')->get(['id', 'name']);
        $data['_application_status'] = ($request->has('_application_status')) ? $request->get('_application_status') : '';
        $data['_application_secondary_status'] = ($request->has('_application_secondary_status')) ? $request->get('_application_secondary_status') : '';
        $data['combine_application'] = $data['_application_status'] == '' ? [] : $data['_application_status'];
        $data['combine_secondary_application'] = $data['_application_secondary_status'] == '' ? [] : $data['_application_secondary_status'];
        $data['application_status'] = array_map('ucfirst', array_keys($this->arraygroup));
        $data['merchant_category'] = MerchantCategory::all();


        $statusLogs = DB::select("
            SELECT application_id, created_at
            FROM (
                SELECT application_id, created_at,
                       ROW_NUMBER() OVER (PARTITION BY application_id ORDER BY created_at DESC) as rn
                FROM status_logs
                WHERE user_id = ?
            ) ranked
            WHERE rn = 1
            ORDER BY created_at DESC
            LIMIT 5
        ", [Auth::user()->id]);


        if(isset($statusLogs[0]->application_id)) {
            $ids = [];
            foreach($statusLogs as $log){
                $ids[] = $log->application_id;
            }
            if($ids) {
                $data['advisor_applications'] = ConsumerApplication::with(['comments' => function ($query) {
                    return $query->with(['user' => function ($query) {
                        return $query->select('id', 'name');
                    }])->orderBy('created_at', 'desc')->select('application_id', 'comment', 'user_id', 'created_at');
                }])->whereIn('id', $ids)->whereNull('is_deleted')->orderBy('updated_at', 'desc')->limit(5)->get(['id', 'name', 'state']);
            }
        }

        return $data;
    }

    public function fetchAadharData(Request $request)
    {
        $data = $request->only(['mobile_number', 'user_id', 'application_id','aadhaar_card','applicant_type', 'number_type']);
        $applicant_type = $data['applicant_type'] == "applicant" ? 1 : 2;
        $resp = $this->getAadharMobileLinkStatus($data['application_id'], $data, $applicant_type);

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

    }

    public function getAadharMobileLinkStatus($application_id, $data = [], $applicant_type = null)
    {
        $latestResponse = ApiResponse::where('application_id', $application_id)
            ->where('applicant_type', $applicant_type)
            ->where('number_type', $data['number_type'])
            ->orderBy('id', 'desc')
            ->whereNull('deleted_at')
            ->first();

        // Determine text label based on number type
        $numberTypeText = (isset($data['number_type']) && $data['number_type'] == 'aadhar_linked_mobile') 
            ? "Aadhar Mobile" 
            : "Comm Mobile";

        // Get consumer application with additional data
        $consumerApplication = ConsumerApplication::with('application_additional')
            ->where('id', $application_id)
            ->select('id', 'mobile_number', 'aadhaar_card', 'state', 'co_applicant_mobile_number', 'co_applicant_aadhaar_card')
            ->first();

        // Create application_additional if it doesn't exist
        if (!$consumerApplication->application_additional) {
            $applicationAdditionObject = new ConsumerApplicationAdditional();
            $applicationAdditionObject->application_id = $consumerApplication->id;
            $applicationAdditionObject->save();
            $consumerApplication->application_additional = $applicationAdditionObject;
        }

        // Validate application data
        if (!$consumerApplication || !$consumerApplication->application_additional) {
            return ['status' => 'FAIL', 'message' => "Can't fetch application details", "linked_status" => null];
        }

        if (in_array($consumerApplication->state, $this->statusBeforeApproved)) {
            return ['status' => 'FAIL', 'message' => "Case is not moved to approved", "linked_status" => null];
        }

        // Get mobile number and aadhaar based on applicant type and number type
        $isAadharLinkedMobile = isset($data['number_type']) && $data['number_type'] == 'aadhar_linked_mobile';
        
        if ($applicant_type == 1) {
            $mobile_number = $isAadharLinkedMobile ? ($data['mobile_number'] ?? $consumerApplication->application_additional->aadhar_linked_mobile) : ($data['mobile_number'] ?? $consumerApplication->mobile_number);
            $aadhaar_card = $data['aadhaar_card'] ?? $consumerApplication->aadhaar_card;
        } elseif ($applicant_type == 2) {
            $mobile_number = $isAadharLinkedMobile ? ($data['mobile_number'] ?? $consumerApplication->application_additional->coapplicant_aadhar_linked_mobile) : ($data['mobile_number'] ?? $consumerApplication->co_applicant_mobile_number);
            $aadhaar_card = $data['aadhaar_card'] ?? $consumerApplication->co_applicant_aadhaar_card;
        } else {
            return ['status' => 'FAIL', 'message' => "Not getting applicant's or coapplicant's", "linked_status" => null];
        }

        // Check if we have a valid cached response
        $cachedRequest = $latestResponse ? json_decode($latestResponse->request, true) : null;
        $cachedResponse = $latestResponse ? json_decode($latestResponse->response, true) : null;
        
        if (isset($cachedRequest['aadhaar_number'], $cachedRequest['mobile_number'], $cachedResponse['status'])) {
            if ($cachedRequest['aadhaar_number'] == $aadhaar_card && 
                $cachedRequest['mobile_number'] == $mobile_number && 
                $cachedResponse['status'] == 'SUCCESS') {
                return [
                    'status' => 'OK',
                    'message' => "Aadhaar link status Already fetched successfully",
                    'linked_status' => $latestResponse->linked_status
                ];
            } else {
                $latestResponse->delete();
            }
        } else {
            if ($latestResponse) {
                $latestResponse->delete();
            }
        }

        $user_id = Auth::user()->id ?? 107;

        // Validate required fields
        if (empty($mobile_number) || empty($aadhaar_card)) {
            $this->updateLinkedStatus($consumerApplication, $applicant_type, $isAadharLinkedMobile, null);
            return ['status' => 'FAIL', 'message' => "Mobile number or Aadhaar card is missing", "linked_status" => null];
        }

        // Make API request
        $requestID = (new TestImport(new Request()))->random_strings(8);
        $request = new Request([
            'reference_id' => $requestID,
            'aadhaar_number' => $aadhaar_card,
            'mobile_number' => $mobile_number,
            'consent' => true,
            'purpose' => 'For Aadhaar Verification',
            'id' => $application_id
        ]);

        $decentro = new DecentroController($request);
        $response = $decentro->getAadharMobileLinkStatus($request);

        // Handle API failure
        if (!$response) {
            $this->updateLinkedStatus($consumerApplication, $applicant_type, $isAadharLinkedMobile, 0);
            $this->logApiResponse($application_id, null, $request->all(), ['error' => 'Failed to fetch response'], 0, $user_id, $applicant_type, $data['number_type'] ?? null);
            return ['status' => 'FAIL', 'message' => "Technical error while fetching Aadhaar link status", "linked_status" => null];
        }

        // Process API response
        $responseArray = [
            'status' => $response->status ?? '',
            'data' => (array)($response->data ?? []),
            'status_code' => $response->status_code ?? ''
        ];

        $linkedStatus = 0;
        $message = "Technical error while fetching Aadhaar link status";

        if ($responseArray['status'] === 'SUCCESS' && ($responseArray['data']['status'] ?? '') === "SUCCESS") {
            $maskedMobile = $responseArray['data']['maskedMobileNumber'] ?? '';
            $last3Masked = substr($maskedMobile, -3);
            $last3Mobile = substr($mobile_number, -3);

            if ($last3Masked === $last3Mobile) {
                $linkedStatus = 1;
                $message = $numberTypeText . " matches with the Aadhaar linked mobile number " . $maskedMobile;
            } else {
                $linkedStatus = 2;
                $message = $numberTypeText . " does not match with the Aadhaar linked mobile number " . $maskedMobile;
            }
        }

        // Update linked status in database
        $this->updateLinkedStatus($consumerApplication, $applicant_type, $isAadharLinkedMobile, $linkedStatus);
        
        // Get the final linked status value
        $finalLinkedStatus = $this->getLinkedStatus($consumerApplication, $applicant_type, $isAadharLinkedMobile);

        // Log the API response
        $this->logApiResponse($application_id, $response->decentroTxnId ?? null, $request->all(), $response, $linkedStatus, $user_id, $applicant_type, $data['number_type'] ?? null);

        return ['status' => 'OK', 'message' => $message, "linked_status" => $finalLinkedStatus];
    }

    private function updateLinkedStatus($consumerApplication, $applicant_type, $isAadharLinkedMobile, $status)
    {
        if ($applicant_type == 1) {
            if ($isAadharLinkedMobile) {
                $consumerApplication->application_additional->linked_mobile_to_aadhar_status = $status;
            } else {
                $consumerApplication->application_additional->linked_status = $status;
            }
        } elseif ($applicant_type == 2) {
            if ($isAadharLinkedMobile) {
                $consumerApplication->application_additional->coapp_linked_mobile_to_aadhar_status = $status;
            } else {
                $consumerApplication->application_additional->co_linked_status = $status;
            }
        }
        
        $consumerApplication->application_additional->save();
    }

    private function getLinkedStatus($consumerApplication, $applicant_type, $isAadharLinkedMobile)
    {
        if ($applicant_type == 1) {
            return $isAadharLinkedMobile 
                ? $consumerApplication->application_additional->linked_mobile_to_aadhar_status
                : $consumerApplication->application_additional->linked_status;
        } elseif ($applicant_type == 2) {
            return $isAadharLinkedMobile 
                ? $consumerApplication->application_additional->coapp_linked_mobile_to_aadhar_status
                : $consumerApplication->application_additional->co_linked_status;
        }
        
        return null;
    }

    private function logApiResponse($application_id, $decentro_txn_id, $request, $response, $linked_status, $user_id, $applicant_type, $number_type = null)
    {
        DB::table('api_responses')->insert([
            'application_id' => $application_id,
            'vendor_id' => $decentro_txn_id,
            'request' => json_encode($request),
            'response' => json_encode($response),
            'created_by' => $user_id,
            'applicant_type' => $applicant_type,
            'number_type' => $number_type,
            'created_at' => Carbon::now()->toDateTimeString(),
            'updated_at' => Carbon::now()->toDateTimeString()
        ]);
    }

    public function getAadharMaskedMobile($application_id, $linked_status, $applicant_type, $number_type = null){
        $latestResponse = DB::table('api_responses')
            ->where('application_id', $application_id)
            ->where('applicant_type', $applicant_type)
            ->where('number_type', $number_type)
            ->orderBy('id', 'desc')
            ->whereNull('deleted_at')
            ->first();

        $message = null;
        $maskedMobile = null;

        if(isset($number_type) && $number_type == 'aadhar_linked_mobile'){
            $text = "Aadhar Mob";
        }else{
            $text = "Comm Mob";
        }

        if ($latestResponse) {
            $responseData = json_decode($latestResponse->response, true);

            if (isset($responseData['data']['maskedMobileNumber'])) {
                $maskedMobile = $responseData['data']['maskedMobileNumber'];
            }
        }
        if($linked_status == 1){
            $message = $text." matches with the aadhar linked mobile number " . $maskedMobile;
        }else if ($linked_status == 2){
            $message = $text." does not matches with the aadhar linked mobile number " . $maskedMobile;
        }else if ($linked_status === 0){
            $message = $text." & Aadhar link failed due to technical reason";
        }
        if($applicant_type == 2 && isset($message)){
            $message = "Co-" . $message;
        }
        return $message;
    }

    public function checkMobileWithAadhar($application_id, $application_status){
        $data = ['number_type' => 'comm_mobile'];

        $resp = $this->getAadharMobileLinkStatus($application_id, $data, 1);
        if(isset($application_status->co_applicant_aadhaar_card) && isset($application_status->co_applicant_mobile_number)){
            $co_resp = $this->getAadharMobileLinkStatus($application_id, $data, 2);
        }

        $data = ['number_type' => 'aadhar_linked_mobile'];

        $resp = $this->getAadharMobileLinkStatus($application_id, $data, 1);
        if(isset($application_status->co_applicant_aadhaar_card) && isset($application_status->application_additional->coapplicant_aadhar_linked_mobile)){
            $co_resp = $this->getAadharMobileLinkStatus($application_id, $data, 2);
        }
    }

    public function getDiscomsData(){
        $data['discoms'] = [
            ["state" => "Andhra Pradesh", "name" => "Southern Power Distribution Company of Andhra Pradesh Limited", "code" => "APSPDCL"],
            ["state" => "Andhra Pradesh", "name" => "Eastern Power Distribution Company of Andhra Pradesh Limited", "code" => "APEPDCL"],
            ["state" => "Assam", "name" => "Assam Power Distribution Company Limited", "code" => "APDCL"],
            ["state" => "Bihar", "name" => "North Bihar Power Distribution Company Limited", "code" => "NBPDCL"],
            ["state" => "Bihar", "name" => "South Bihar Power Distribution Company Limited", "code" => "SBPDCL"],
            ["state" => "Calcutta", "name" => "Calcutta Electric Supply Corporation Limited", "code" => "CESC"],
            ["state" => "Chandigarh", "name" => "Chandigarh Electricity Department", "code" => "CH_ELEC"],
            ["state" => "Chhattisgarh", "name" => "Chhattisgarh State Power Distribution Company Limited", "code" => "CSPDCL"],
            ["state" => "Daman & Diu", "name" => "Daman and Diu Electricity Department", "code" => "DAMAN_DIU"],
            ["state" => "Delhi", "name" => "Tata Power Delhi Distribution", "code" => "TATA_DL"],
            ["state" => "Delhi", "name" => "BSES Yamuna Power Ltd / BSES Rajdhani Power Ltd", "code" => "BSES_DL"],
            ["state" => "Goa", "name" => "Goa Electricity- for Tisvadi, Ponda & Verna", "code" => "GOA_ELEC"],
            ["state" => "Goa", "name" => "Goa Electricity- for others", "code" => "UPAY_GOA"],
            ["state" => "Gujarat", "name" => "Uttar Gujarat VIJ Company Ltd.", "code" => "UGVCL"],
            ["state" => "Gujarat", "name" => "Pashchim Gujarat VIJ Company Ltd.", "code" => "PGVCL"],
            ["state" => "Gujarat", "name" => "Madhya Gujarat VIJ Company Limited", "code" => "MGVCL"],
            ["state" => "Gujarat", "name" => "Dakshin Gujarat VIJ Company Limited", "code" => "DGVCL"],
            ["state" => "Gujarat", "name" => "Torrent Power Limited - Ahmedabad", "code" => "TORRENT_AHD"],
            ["state" => "Gujarat", "name" => "Torrent Power Limited - Surat", "code" => "TORRENT_SURAT"],
            ["state" => "Gujarat", "name" => "Torrent Power Limited - Agra", "code" => "TORRENT_AGRA"],
            ["state" => "Gujarat", "name" => "Torrent Power Limited - Bhiwandi", "code" => "TORRENT_BHIWANDI"],
            ["state" => "Gujarat", "name" => "Torrent Power Limited - Dahej", "code" => "TORRENT_DAHEJ"],
            ["state" => "Haryana", "name" => "Dakshin Haryana Bijli Vitran Nigam", "code" => "DHBVN"],
            ["state" => "Haryana", "name" => "Uttar Haryana Bijli Vitran Nigam", "code" => "UHBVN"],
            ["state" => "Himachal Pradesh", "name" => "Himachal Pradesh State Electricity Board Ltd", "code" => "HPSEB"],
            ["state" => "Jharkhand", "name" => "Jharkhand Bijli Vitran Nigam Limited", "code" => "JBVNL"],
            ["state" => "Karnataka", "name" => "Mangalore Electricity Supply Company Limited", "code" => "MESCOM"],
            ["state" => "Karnataka", "name" => "Bangalore Electricity Supply Company Ltd", "code" => "BESCOM"],
            ["state" => "Karnataka", "name" => "Chamundeshwari Electricity Supply Company Limited Mysore", "code" => "CESCOM"],
            ["state" => "Karnataka", "name" => "Gulbarga Electricity Supply Company Limited", "code" => "GESCOM"],
            ["state" => "Karnataka", "name" => "Hubli Electricity Supply Company Limited", "code" => "HESCOM"],
            ["state" => "Kerala", "name" => "Kerala State Electricity Board", "code" => "KERALA"],
            ["state" => "Madhya Pradesh", "name" => "Madhya Pradesh Paschim Kshetra Vidyut Vitran Company Limited", "code" => "MPWZ"],
            ["state" => "Madhya Pradesh", "name" => "Madhya Pradesh Madhya Kshetra Vidyut Vitran Company Limited", "code" => "MPCZ"],
            ["state" => "Madhya Pradesh", "name" => "Madhya Pradesh Poorv Kshetra Vidyut Vitran Company Limited", "code" => "MPEZ"],
            ["state" => "Maharashtra", "name" => "TATA-Power - Mumbai", "code" => "TATA_MUMBAI"],
            ["state" => "Maharashtra", "name" => "MAHAVITARAN-Maharashtra State Electricity Distribution Co. Ltd (MSEDCL)", "code" => "MAHAVITRAN"],
            ["state" => "Maharashtra", "name" => "Brihanmumbai Electric Supply & Transport Undertaking for Greater Mumbai", "code" => "BEST_MH"],
            ["state" => "Meghalaya", "name" => "Meghalaya Energy Corporation Limited", "code" => "MeECL"],
            ["state" => "Orissa", "name" => "Supply Company of Orissa Limited (North, South, West, Central)", "code" => "ORISSA"],
            ["state" => "Punjab", "name" => "Punjab State Power Corporation Limited", "code" => "PSPCL"],
            ["state" => "Rajasthan", "name" => "Jaipur Vidhyut Vitran Nigam Ltd", "code" => "JAIPUR"],
            ["state" => "Rajasthan", "name" => "Ajmer Vidhyut Vitran Nigam Ltd", "code" => "AJMER"],
            ["state" => "Rajasthan", "name" => "Jodhpur Vidhyut Vitran Nigam Ltd", "code" => "JODHPUR"],
            ["state" => "Tamil Nadu", "name" => "Tamil Nadu Generation and Distribution Corporation Limited - Chennai_North", "code" => "CHENNAI_NORTH"],
            ["state" => "Tamil Nadu", "name" => "Tamil Nadu Generation and Distribution Corporation Limited - Chennai_South", "code" => "CHENNAI_SOUTH"],
            ["state" => "Telangana", "name" => "The Southern Power Distribution Company of Telangana Limited", "code" => "TSSPCL"],
            ["state" => "Tripura", "name" => "Tripura State Electricity Corporation Limited", "code" => "TRIPURA"],
            ["state" => "Uttar Pradesh", "name" => "Kanpur Electricity Supply Company", "code" => "KESCO"],
            ["state" => "Uttar Pradesh", "name" => "UP Vidyut Vitran Nigam Limited (All Zones)", "code" => "UPPCL"],
            ["state" => "West Bengal", "name" => "West Bengal State Electricity Distribution Company Limited", "code" => "WBENGAL"],
            ["state" => "Nagaland", "name" => "Department of Power, Nagaland", "code" => "NAGALAND"],
            ["state" => "Mizoram", "name" => "Government of Mizoram Power & Electricity Department", "code" => "MIZORAM"],
            ["state" => "Karnataka", "name" => "Hukkeri Rural Electricity Cooperative Society Ltd", "code" => "HUKKERI"],
            ["state" => "Jharkhand", "name" => "Jharkhand Bijli Vitran Nigam Limited", "code" => "JBVNL"],
            ["state" => "Telangana", "name" => "The Northern Power Distribution Company of Telangana Limited", "code" => "TGNPDCL"],
            ["state" => "Odisha", "name" => "TP Central Odisha Distribution Limited", "code" => "ORISSA_CENTRAL"],
            ["state" => "Odisha", "name" => "TP Northern Odisha Distribution Limited", "code" => "ORISSA_NORTH"],
            ["state" => "Odisha", "name" => "TP Southern Odisha Distribution Limited", "code" => "ORISSA_SOUTHERN"],
            ["state" => "Odisha", "name" => "TP Western Odisha Distribution Limited", "code" => "ORISSA_WESTERN"],
            ["state" => "Manipur", "name" => "Manipur State Power Distribution Company Limited", "code" => "MANIPUR"],
        ];

        // Districts mapped to their respective discoms
        $data['discom_districts'] = [
            'UP Vidyut Vitran Nigam Limited (All Zones) (UPPCL)' => [
                "Agra", "Aligarh", "Ambedkar Nagar", "Amethi", "Amroha", "Auraiya",
                "Ayodhya", "Azamgarh", "Bagpat", "Bahraich", "Ballia", "Balrampur",
                "Banda", "Bara Banki", "Bareilly", "Basti", "Bijnor", "Budaun",
                "Bulandshahr", "Chandauli", "Chitrakoot", "Deoria", "Etah", "Etawah",
                "Ghazipur", "Gonda", "Gorakhpur", "Hamirpur", "Hapur District", "Farrukhabad",
                "Fatehpur", "Firozabad", "Gautam Buddha Nagar", "Ghaziabad", "Hardoi", "Hathras",
                "Jalaun", "Jaunpur", "Jhansi", "Kannauj", "Kanpur Dehat", "Kanpur Nagar",
                "Kasganj", "Kaushambi", "Lakhimpur Kheri", "Lalitpur", "Lucknow", "Mahoba",
                "Maharajganj", "Mainpuri", "Mathura", "Mau", "Meerut", "Mirzapur",
                "Moradabad", "Muzaffarnagar", "Pilibhit", "Pratapgarh", "PrayagRaj", "Raebareli",
                "Rampur", "Saharanpur", "Sambhal", "Sant Kabir Nagar", "Sant Ravidas Nagar Bhadohi",
                "Shahjahanpur", "Shamli", "Shravasti", "Siddharthnagar", "Sitapur", "Sonbhadra",
                "Sultanpur", "Unnao", "Varanasi"
            ],
            'Jharkhand Bijli Vitran Nigam Limited (JBVNL)' => [
                "Adityapur-1", "Adityapur -2", "Amrapada", "Ashok nagar", "Barharwa",
                "Barhi Hazaribagh", "Barkatta", "Barwadda", "Barwahdih", "Basukinath",
                "Basukinath(Jamtara)", "Bermo", "Bermo(Tenughat)", "Bhurkunda", "Bundu",
                "Chaibasa(Rural)", "Chaibasa(Urban)", "Chakradharpur", "Chakulia",
                "Chandankiyari", "Chandil", "Chas(Rural)", "Chas(Urban)", "Chatra(North)",
                "Chatra(South)", "Chhatarpur", "Chhatarpur(Daltonganj)", "Chhotagovindpur",
                "Chirkunda", "Chouparan", "Chouparan(Hazaribagh)", "Daltonganj(Rural)",
                "Daltonganj(Urban)", "Deoghar", "Deoghar-1", "Deoghar-2", "Dhalbugarh",
                "Dhigwadih", "Domchanch", "Domchanch(KODERMA)", "Doranda", "Dumka(Rural)",
                "Dumka(Urban)", "Dumri", "DVM", "Ganeshpur", "Garhwa I", "Garhwa II",
                "Ghagra", "Ghatshila", "Giridih(Rural)", "Giridih(Urban)", "Godda",
                "Godda (Godda)", "Goelkera", "Gola", "Gomoh", "Govindpur", "Gumla",
                "Harmu", "Hazaribagh(Rural)", "Hazaribagh(Urban)", "HEC", "Hirapur",
                "Jadugora", "Jainamore", "Jamtara", "Jamua", "Japla", "Japla(Daltonganj)",
                "Jasidih", "Jasidih(Deoghar)", "Jharia", "Jhumari Telaiya","Jhumari Telaiya(Koderma)","JSR(Karandih)","Jugsali","Kamdara","Kanke","Karkend","Kathara (Gomia)","Katkamsandi","Katras","Khunti","Koderma","Koderma (Koderma)","Kokar","Kolebira","Kujju","Kuru","Lalpur","Latehar","Lohardaga","Loyabad","Madhupur","Madhupur(Deoghar)","Mahagama","Mahgama","Main Road","Mandar","Mango","Mango-1","Mango-2","Manjhari","Manoharpur","Mihijam","Mukunda","Nagaruntari","Navamundi","Naya Bazaar","Nirsa 1","Nirsa 2","Ormanjhi","Pakur","Pakur(Rural)","Patan","Rajdhanwar","Rajkarsava","Rajmahal","Ramgarh","Ratu chatti","Ratu Road","RMCH","Sahebganj(Rural)","Sahebganj","Saraikela","Sarat","Sarat(Deoghar)","Saria","Simdega","Sindri","Tatisilwai","Tinpahar","Tisri","Topchanchi","Torpa","Tundi","Tupudana","Upper Bazaar",
            ],
            "Manipur State Power Distribution Company Limited (MANIPUR)" => [
                "Bishnupur SD","Boro Bekra","Central Sub-Division I & II","Chandel","Churachandpur Distribution/Sub-Division","Jiribam","Kakching Sub-Division","Kamjong","Kangpokpi","Kongba","Kumbi SD","Kwakeithel Sub-Division I & II","Lamlai","Lamlong I & II Sub-Division","Lamphel Sub-Division I & II","Leimakhong","Lilong Sub-Division","Litan","Mao Tadubi","Moirang SD","Moreh","Nambol SD","Noney SD","Parbung","Pherzawl","Phungyar","Rural Electrification","Sagolmang","Saikul","Senapati Sub-Division","Singjamei","Sugnu Sub-Division","Takyel Sub-Division","Tamei SD","Tamenglong SD","Tengnoupal","Thanlon","Thoubal","Tousem Sub-Division","Ukhrul","Wangjing Sub-Division","Wangkhei","Wangoi Sub-Division","Yairipok Sub-Division",
            ],
        ];

        // Discoms that require only the mobile input field
        $data['discoms_require_mobile'] = [
            'Kerala State Electricity Board (KERALA)'
        ];
        return $data;
    }
    
    public function showPostDisbursement($id, $field = null){
        if(Session::has('Post_Disbursement_View|-52') && $field){

            $status_log = StatusLogs::where('application_id', $id)->where('status', 'disbursed')->first(['id']);
            if(!isset($status_log->id)){
                return true;
            }
            
            $pre_defined_field = [
                'pan_card',
                'dob',
                'mobile_number',
                'email',
                'gender',
                'first_name',
                'middle_name',
                'last_name',
                'applicant_address',
                'aadhaar_card_number',
                'k. Employment details',
                'Credit Report',
                'Credit limit',
                'Credit report sub-section' ,
                'Credit Report (Equifax and CIBIL)',
                'Co-Applicant Details',
                'co_applicant_name',
                'co_applicant_gender',
                'co_applicant_pan_card',
                'co_applicant_aadhar_card_number',
                'co_applicant_address',
                'Employment details',
                'foir_section'
            ];
            
            return $pre_defined_field[$field];
        }

        return false;
    }

    public function getCaseWiseData(Request $request)
    {
        $questionId = 1577;
        $applicationId = $request->input('application_id');
        // $applicationId = 268459;
        $distanceInKm = $request->input('distance_in_km');

        $parameters = [
            'application_id' => $applicationId,
            'distance_in_km' => $distanceInKm,
        ];

        // Define the parameter types for this specific question.
        $parameterTypes = [
            'application_id' => 'number',
            'distance_in_km' => 'number',
        ];

        $metabase = new MetabaseController();
        $data = $metabase->getMetabaseData($questionId, $parameters, $parameterTypes);

        return $data;
    }

    public function getJSONBRELogs(Request $request){
        try{
            $response = (new JSONBREController())->fetchLatestJsonBreResponse($request->get('application_id'));
            if (is_array($response)) {
                $res = [];
                foreach ($response as $val) {
                    $decoded = (array) json_decode($val->response);
                    if (is_array($decoded)) {
                        $res = array_merge($res, $decoded);
                        $request_batch_id = $val->request_batch_id;
                    }
                }
            } else {
                $res = (array) json_decode($response->response);
            }

            if(!$res) {
                return response()->json(['status' => 'OK', 'data' => 'No Json BRE Called'], 200);
            }

            $policies = [];
            foreach ($res as $policy => $_res) {
                if ($policy !== 'status') {
                    $explodeString = explode('-', $policy);
                    $policies[] = end($explodeString);
                }
            }
            $ruleName = ApprovalRule::whereIn('id', $policies)->get(['rule_name','id', 'grade_id']);
            $ruleNameList = [];
            $ruleNameGradeIds = [];
            foreach($ruleName as $_rule_name){
                $ruleNameList[$_rule_name->id] = $_rule_name->rule_name;
                $ruleNameGradeIds[$_rule_name->id] = $_rule_name->grade_id;
            }
            $ruleNameList['-1'] = 'rejection';

            $data = [];
            foreach ($res as $policy => $_res) {
                if ($policy === 'status') {
                    continue;
                }
                $policyNameString = explode('-', $policy);
                $policyId = end($policyNameString);

                $rules = [];
                foreach ($_res->rules as $rule) {
                    $against_condition = '';
                    if ($rule->reason != 'Value not found in s3') {
                        $against_value = !is_array($rule->against[0]) ? $rule->against[0] : $rule->against[0][0].'<br/> Remark: '.$rule->against[0][1];
                        $against_condition = 'Value: '.$against_value.'<br/> Condition: '.$rule->against[1];
                    }

                    // Source value
                    if ($rule->reason == 'Value not found in s3') {
                        $source_value = '';
                    } elseif (is_array($rule->source)) {
                        $source_value = $rule->source[0] . ' and ' . $rule->source[1];
                    } else {
                        $source_value = $rule->source;
                    }

                    // Logs column - only populated for bureau_surrogate rule
                    $logs_display = '';
                    if ($rule->key === 'bureau_surrogate' && isset($rule->log) && !empty($rule->log) && $rule->reason != 'Value not found in s3') {
                        if (is_array($rule->log)) {
                            $log_items = [];
                            foreach ($rule->log as $log_item) {
                                if (is_object($log_item) && get_class($log_item) === 'stdClass') {
                                    // Handle stdClass objects like {"Auto Loan": 224562.6}
                                    $formatted_log = [];
                                    foreach ($log_item as $key => $value) {
                                        $formatted_log[] = htmlspecialchars($key) . ': ' . htmlspecialchars($value);
                                    }
                                    $log_items[] = implode(', ', $formatted_log);
                                } else {
                                    // Handle simple values
                                    $log_items[] = htmlspecialchars($log_item);
                                }
                            }
                            $logs_display = implode('<br/>', $log_items);
                        } else {
                            $logs_display = htmlspecialchars($rule->log);
                        }
                    }

                    $rules[] = [
                        'key'               => str_replace('_', ' ', $rule->key),
                        'reason'            => $rule->reason,
                        'against_condition' => $against_condition,
                        'source_value'      => $source_value,
                        'result'            => $rule->result ? 'Yes' : 'No',
                        'logs'              => $logs_display,
                    ];
                }

                $policyPassed = JsonBREApprovalStatusLog::where('application_id', $request->get('application_id'))->where('status', 1)->where('request_batch_id', $request_batch_id)->pluck('rule_id')->toArray();
                $eligibleNetLoanAmount = in_array($policyId, $policyPassed) ? (new JsonBREController())->calculateEligibleAmount($policyId, $request->get('application_id')) : 0;

                $policyStatus = ($_res->policy_status && ($eligibleNetLoanAmount >= 50000 && $eligibleNetLoanAmount <= 500000)) ? 'Approved' : 'Rejected';

                $data[] = [
                    'policy'          => $policy,
                    'policy_name'     => $ruleNameList[$policyId] ?? $policy,
                    'policy_status'   => $policyStatus,
                    'grade_id'        => $ruleNameGradeIds[$policyId] ?? 0,
                    'eligible_net_loan_amount' => $eligibleNetLoanAmount,
                    'rules'           => $rules,
                ];
            }

            $body = view('admin.consumer-application.json-bre-logs', ['data' => $data])->render();

            return response()->json(['status' => 'OK', 'data' => $body], 200);
        } catch (\Exception $e) {
            (new Slack(new Request(['title'=>'JSON BRE logs display error','fields'=>['error'=>$e->getMessage(),'line'=>$e->getLine(),'trace'=>$e->getTraceAsString()], 'group' => Slack::$STAGE_TESTING])))->send();
            $message = 'JSON BRE failed, please contact the tech support at support@creditfair-desk.freshdesk.com';
            return response()->json(['status' => 'OK', 'data' => $message], 200);
        }
    }



    public function checkRevocationList(){

        $list = RevocationList::where('application_id', request()->get('id'))->where('phone', request()->get('mobile'))->first(['id', 'status']);
        if(isset($list->id)){
            return response()->json(['status' => 'OK', 'message' => 'Fetched successfully', 'response' => ['status' => $list->status]]);
        }


        $curl = curl_init();
        $karza_key = (_env('KARZAKEY_REVOCATION', ''));

        $user_id = $user = Auth::check() ? Auth::user()->id : 107;

        $payload = json_encode(['mobile' => request()->get('mobile'), 'consent' => 'y', 'clientData' => ['caseId' => request()->get('id')]]);

        curl_setopt_array($curl, array(
            CURLOPT_URL => _env('KARZA_MNRL_REVOCATION'),
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => $payload,
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json',
                'x-karza-key: '.$karza_key
            ),
        ));

        $response = curl_exec($curl);

        $response = json_decode($response);

        curl_close($curl);

        (new Slack(new \Illuminate\Http\Request(['title' => 'KARZA_MNRL_REVOCATION Res', 'fields' => ['req' => $payload,'res' => json_encode($response)]])))->send();

        $status = 'FAIL';
        $active = null;
        $message = 'Failed to fetch the list';
        if((isset($response->result) && isset($response->result->active) && $response->result->active) || (isset($response->statusCode) && $response->statusCode == 103)){
            $status = 'OK';
            $active = (isset($response->result->active) && $response->result->active == 'n') ? 0 : (isset($response->result->active) && $response->result->active == 'y' ? 1 : null);
            $message = 'Fetched successfully';

            $revocation = new RevocationList();
            $revocation->fill(
                [
                    'application_id' => request()->get('id'),
                    'phone' => request()->get('mobile'),
                    'type' => request()->get('type'),
                    'user_id' => $user_id,
                    'status' => $active,
                    'response' => json_encode($response)
                ]
            );

            $revocation->save();
        }else{
            $message = $response->message ?? $message;
        }

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

    public function getFundlyLoans(){
        $customers = DB::table('fundly_customer_loans')->paginate(10);
        return view('admin.fundly.index', ['customers' => $customers]);
    }

    public function getFundlyLoan($id){

        $customer = DB::table('fundly_customer_loans')->where('id', $id)->first();
        $documents = DB::table('fundly_customer_documents')->where('customer_id', $customer->customer_id)->get();
        return view('admin.fundly.edit', ['customer' => $customer, 'documents'=> $documents]);
    }

    public function showFundlyDoc($id){
        $document = DB::table('fundly_customer_documents')->where('id', $id)->first();
        $url = Storage::disk('s3_fundly')->temporaryUrl(
            $document->file_path,    // S3 key
            now()->addMinutes(5)   // Expiration time
        );

        return redirect($url);
    }

    public function getMerchantRiskData(){
        if (_env('MERCHANT_MIGRATION_ACTIVE')) {
            $user  = Auth::user();
            $email = $user ? $user->email : 'admin@creditfair.in';
            $role  = $user ? $user->user_type : 'admin';
            $token = generateCreditFairToken($email, $role);
            $baseUrl = _env('MIGRATED_MERCHANT_RISK_URL', 'http://localhost:3000/#/admin/merchant-risk/gross');

            $data['iframeUrl'] = $baseUrl . '?token=' . urlencode($token) . '&hide_sidebar=true'; 
            $data['sidebar']   = 'merchant_risk'; // Using standard sidebar identifier
            
            return view('admin.accounting.merchant_risk_index_migrated', $data);
        }

        $input_file = ['adjustments_data.xlsx', 'fintech_sheet.xlsx', 'jify_score.xlsx', 'jify_state.xlsx', 'lender_name_change_file.xlsx', 'lender_pos_dpd_change.csv', 'previous_month_mr.csv'];

        return view('admin.accounting.merchant_risk_index', ['input_files' => $input_file, 'from_date' => Carbon::now()->toDateString()]);
    }

    public function runMerchantRiskData(Request $request){
        ini_set('max_execution_time', -1);
        set_time_limit(0);
        ini_set('memory_limit', '-1');
        $curl = curl_init();

        $files = $_FILES;
        $fileFields = [];

        foreach($files as $i => $fileName) {
            $tmpName = $files[$i]['tmp_name'];
            $name = $files[$i]['name'];
            $type = mime_content_type($tmpName);
            
            $fileFields["files[$i]"] = new \CURLFile($tmpName, $type, $name);
        }
        $fileFields['date'] = $request->get('from_date');

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

        $response = curl_exec($curl);

        curl_close($curl);

        $status = 'OK';

        if(isset($response->status)){
            $this->downloadZipRiskFile();
        }

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

    public function downloadZipRiskFile(){
        $url =_env('PY_SCRIPT_SERVER_HOST').'/download-zip';

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_HEADER, true);

        $response = curl_exec($ch);
        $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
        $headers = substr($response, 0, $header_size);
        $body = substr($response, $header_size);

        
        $filename = "output.zip";
        if (preg_match('/filename="(.+?)"/', $headers, $matches)) {
            $filename = $matches[1];
        }

        curl_close($ch);

        // Set headers to force download in browser
        header("Content-Type: application/zip");
        header("Content-Disposition: attachment; filename=\"$filename\"");
        header("Content-Length: " . strlen($body));

        echo $body;
        exit;
    }

    public function fetchAAReportMonitoring(Request $request){
        if($request->has('application_id')){
            $accountAggregator = new AccountAggregator($request);
            return $accountAggregator->autoFetchStatementForMonitoring();
        }
        return response()->json(['status' => 'FAIL', 'message' => 'Invalid app id']);
    }

    public function updateAAReportMonitoring(Request $request){
        if($request->has('account_aggregator_monitoring_id')){
            $accountAggregator = new AccountAggregator($request);
            if($response = $accountAggregator->updateSubsidyStatus()){
                return response()->json(['status' => 'OK', 'message' => 'AA Status changed successfully']);
            }
        }
        return response()->json(['status' => 'FAIL', 'message' => 'Invalid app id or No AA initiated for monitoring']);
    }

    public function updateFetchDateMonitoring(Request $request){
        if($request->has('account_aggregator_monitoring_id') && $request->has('next_fetch_date')){
            $accountAggregator = new AccountAggregator($request);
            if($response = $accountAggregator->updateAutoFetch()){
                return response()->json(['status' => 'OK', 'message' => 'AA Status changed successfully']);
            }
        }
        return response()->json(['status' => 'FAIL', 'message' => 'Invalid app id or No AA initiated for monitoring']);
    }

    public function initiateAAMonitoringRequest($id, $source){
        $request = new Request();
        $accountAggregatorService = new AccountAggregator($request);

        $isTrancheDisbursement = $accountAggregatorService->isTrancheDisbursement($id);

        $shouldProcess =
            ($source === 'disbursal' && !$isTrancheDisbursement) ||
            ($source === 'document_upload' && $isTrancheDisbursement);

        if ($shouldProcess) {
            $accountAggregatorLists = AccountAggregatorModel::where('application_id', $id)
                ->where('is_monitoring', 1)
                ->get(['id', 'referenceId', 'is_monitoring', 'trackingId']);

            foreach ($accountAggregatorLists as $account_aggregator) {
                $accountAggregatorService->initMonitoring($account_aggregator);
            }
        }

    }

    public function updateFrequencyForMonitoring(Request $request)
    {
        if ($request->get('frequency') && $request->get('frequency') > 0){
            DB::table('account_aggregator_config')->update(['auto_fetch_frequency' => $request->get('frequency')]);
        }
        return response()->json(['status' => 'OK', 'message' => 'Frequency Updated']);
    }

    public function triggerKYCReview(Request $request)
    {
        try {
            $application_id = $request->get('application_id');
            $user = $request->get('user');
            $applicant_type = $user == 'Co-Applicant' ? 2 : 1;
            
            $merchant = DB::selectOne("SELECT m.merchant_name from merchant m inner join consumer_application ca on m.id = ca.merchant_id where ca.id = ?", [$request->get('application_id')]);
            $emailList = _env('DISBURSEMENT_EMAIL');

            $reviewLink = _env('APP_URL') . '/admin/consumer-checklist-data/' . $application_id . '/get';

            $body = '
                    <div style="font-size:13px;font-family:verdana,arial;line-height:1.5">
                    Dear Disburesement Team,<br><br>
                    The self attested KYC documents for POA & POI are uploaded by ' . $user .' for below details.<br> 
                    Application ID - ' . $request->get('application_id') . '<br>
                    Merchant ID - ' . $merchant->merchant_name . '<br>
                    Type of User - ' . $user . '<br><br>
                    Please review the documents - <a href="' . $reviewLink . '">' . $reviewLink . '</a><br>
                    Commented By: System Generated<br><br>
                    </div>';
            $emails = explode(',', $emailList);
            Mail::send('emails.reminders.basic_reminder',
                ['body' => $body]
                , function ($message) use ($emails, $user) {
                    $message->to($emails)->subject($user.' Self Attested KYC Documents');
            });
            $tag = (new WebhookController())->getCommentTag(null, 31); // disbursement team user type hard coded
            $commentText = $tag."The VKYC has been completed for partner loan id " . $request->get('application_id') . " Documents uploaded by " . $user . " Kindly review the documents";
            $comment = new Comments();
            $comment->application_id = $request->get('application_id');
            $comment->user_id = 107;
            $comment->comment = $commentText;
            $comment->show_merchant = 0;
            $comment->show_consumer = 0;
            $comment->save();
            $consumerApplicationController = new ConsumerApplicationController();
            $consumerApplicationController->webhook($request->get('application_id'), ['type' => 'VKYC-Webhook','status' => 'completed', 'data' => ['vendor'=> 'self-attested', 'applicantType' => $applicant_type]]);

        return response()->json(['status' => 'OK', 'message' => 'Review request sent']);

        }catch (\Exception $e) {
            return response()->json(['status' => 'FAIL', 'message' => $e->getMessage()]);
        }
    }

    private function calculateMerchantRiskMitigation($merchant_id, $applicationElementObject, $consumerApplication = null)
    {
        if ($consumerApplication) {
            $excludedStatuses = ['ready for disbursement', 'disbursed', 'nach registered', 'closed'];
            if (in_array(strtolower(trim($consumerApplication->state)), $excludedStatuses)) {
                return null;
            }
            
            $approvalLog = \App\StatusLogs::where('application_id', $consumerApplication->id)
                ->where('status', 'approved')
                ->orderBy('created_at', 'desc')
                ->first();
                
            if ($approvalLog && strtotime($approvalLog->created_at) < strtotime('2026-08-11 00:00:00')) {
                return null;
            }
        }

        $merchRisk = MerchantRiskMitigation::where('merchant_id', $merchant_id)->first();

        $riskJson = [
            'pm_surayaghar'    => 0,
            'security_cheque'  => 0,
            'solar_power_type' => 0,
            'solar_category'   => 0,
            'solar_location'   => 0
        ];

        if ($merchRisk) {
            $riskJson['pm_surayaghar']   = (int)$merchRisk->pm_surayaghar;
            $riskJson['security_cheque'] = (int)$merchRisk->security_cheque;

            // App value: 'type_of_solar_power' (1=OnGrid, 2=OffGrid, 3=Hybrid)
            $appSolarType = $applicationElementObject->solar_power_type; 
            $allowedPowerTypes = explode(',', $merchRisk->solar_power_type);
            
            if ($appSolarType && in_array($appSolarType, $allowedPowerTypes)) {
                $riskJson['solar_power_type'] = 1;
            }

            // App value: 'type_of_customer' (1=Resi, 2=MSME, etc)
            $appCustomerType = $applicationElementObject->type_of_customer; // This was filled earlier
            $allowedCategories = explode(',', $merchRisk->solar_category);

            if ($appCustomerType && in_array($appCustomerType, $allowedCategories)) {
                $riskJson['solar_category'] = 1;
            }

            // Merchant value: 'MH,GJ,DL' (Comma separated)
            $appStateName = $applicationElementObject->installation_address_state;
            $allowedLocations = explode(',', $merchRisk->solar_location);

            if ($appStateName) {
                $stateModel = StateModel::where('name', $appStateName)->first(['code']);

                if (isset($stateModel->code) && in_array(trim($stateModel->code), array_map('trim', $allowedLocations))) {
                    $riskJson['solar_location'] = 1;
                }
            }
        }

        return json_encode($riskJson);
    }
}
