<?php

namespace App;

use App\Http\Controllers\ApiController;
use App\Http\Controllers\Admin\ConsumerApplicationController;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Http\Request;
use App\Scopes\MessageScope;
use App\Avanse\Services\SubService\CreateCustomer;
use App\Avanse\Services\SubService\CreateFinance;
use App\Avanse\DataModels\AvanseDisbursementInstruction;
use App\Model\Prediction;

class ConsumerApplication  extends Model
{
    use SoftDeletes;
    use Encryptable;

    const AVANSE_LENDER_ID = 3;

    private static $isAccountOpened = false;
    private static $isApplicantType = false;
    public static $isCFFoirNotInclude = false;
    public static $isSubventionInvoice = false;
    public static $isMandateManyFilter = false;
    public static $center_id = 0;
    public static $uniqueRefId = 'avanse_da';
    public static $emi_date = "";

    public static $encryptable = [
        'pan_card',
        'mobile_number',
        'aadhaar_card',
        'co_applicant_aadhaar_card',
        'co_applicant_mobile_number',
        'co_applicant_pan_card',
        'alt_contact_number',
        'company_number',
        'email',
        'co_applicant_email'


    ];

    protected static function boot()
    {
        parent::boot();
        static::addGlobalScope(new MessageScope(static::$encryptable));
    }
    protected $table = 'consumer_application';
    public static $model = 'consumer_application';

    public $fillable = ['user_id', 'merchant_id', 'merchant_location_id', 'name', 'email', 'mobile_number', 'gender', 'tenure', 'purpose', 'src_merchant_name', 'src_representative_name', 'lead_src_email', 'lead_src_phone', 'long_link', 'pan_card', 'aadhaar_card', 'dob', 'marital_status', 'approved_amount', 'loan_amount',
        'current_address_line_1', 'current_address_state', 'current_address_city', 'current_address_pincode', 'current_address_landmark', 'current_address_status',
        'permanent_address_line_1', 'permanent_address_state', 'permanent_address_city', 'permanent_address_pincode', 'permanent_address_landmark', 'permanent_address_status',
        'work_address_line_1', 'work_address_state', 'work_address_city', 'work_address_pincode', 'work_address_landmark',
        'employee_status', 'monthly_income', 'company_name', 'company_number', 'experience', 'contact_address', 'alt_contact_number',
        'co_applicant_name', 'co_applicant_relationship', 'co_applicant_dob', 'co_applicant_gender', 'co_applicant_pan_card', 'co_applicant_aadhaar_card', 'co_applicant_email', 'co_applicant_mobile_number', 'co_applicant_address_line_1', 'co_applicant_address_state', 'co_applicant_address_pincode', 'co_applicant_address_city', 'co_applicant_address_landmark', 'co_applicant_address_status', 'co_applicant_required',
        'co_applicant_employee_status', 'co_applicant_monthly_income', 'co_applicant_company_name', 'co_applicant_company_number', 'co_applicant_experience',
        'state', 'completed_stage', 'credit_score', 'rejection_reason', 'assigned_to', 'misc_info', 'updated_by','created_by','lender_id','offer_id','pre_created_by', 'linked_status'];

    public static function isAccountOpened($boolean){
        static::$isAccountOpened = $boolean;
    }

    public static function isSubventionInvoice($boolean){
        static::$isSubventionInvoice = $boolean;
    }

    public static function isApplicantType($boolean){
        static::$isApplicantType = $boolean;
    }
    public static function setEmiDate($emidate){
        static::$emi_date = $emidate;
    }

    public function merchant()
    {
        return $this->hasOne('App\Merchant','id','merchant_id');
    }

    public function merchant_bank_details(){
        return $this->hasOne('App\MerchantBank','merchant_id','merchant_id');
    }

    public function category()
    {
        return $this->hasOne('App\MerchantCategory','id','purpose');
    }

    public function merchant_location()
    {
        return $this->hasOne('App\MerchantLocation','id','merchant_location_id');
    }

    public function centers()
    {
        return $this->hasMany('App\MerchantLocation','id','merchant_id');
    }

    public function mandate()
    {
        return $this->hasOne('App\Mandate','consumer_application_id','id');
    }

    public function equifax_report()
    {
        return $this->hasOne('App\EquifaxReport','_id','id')->where('id_type','application_id')->where('applicant_type',1);
    }

    public function checkmandate()
    {
        return $this->hasOne('App\Mandate','consumer_application_id','id')->whereNotNull('umrn')->where('umrn','!=','0')->orderBy('mandate_amount','desc')->where('status','active');
    }

    public function monthlymandate()
    {
        return $this->hasOne('App\Mandate','consumer_application_id','id')->whereNotNull('umrn')->where('umrn','!=','0')->where('frequency',"M");
    }

    public function fullmandate()
    {
        return $this->hasOne('App\Mandate','consumer_application_id','id')->whereNotNull('umrn')->where('umrn','!=','0')->where('frequency',"O");
    }

    public function mandateMany(){
        $mandateMany = $this->hasMany('App\Mandate','consumer_application_id','id');
        if (static::$isMandateManyFilter){
            $mandateMany->where('created_at','>=',static::$isMandateManyFilter['from_date'])->where('created_at','<=',static::$isMandateManyFilter['to_date']);
        }
        return $mandateMany;
    }

    public function bank_details()
    {
        return $this->hasOne('App\Bank','application_id','id')->where('applicant_type',1);
    }

    public function document_details(){
        return $this->hasMany('App\DocumentDetails','application_id','id');
    }

    public function bank_details_multiple()
    {
        return $this->hasMany('App\Bank','application_id','id')->orderBy('applicant_type','asc');
    }

    public function emi()
    {
        return $this->hasOne('App\ApplicationEMICalculation','application_id','id');
    }

    public function proFormaInvoice(){
        return $this->hasOne('App\ProFormaInvoice','application_id','id');
    }

    public function creditReport(){
        $creditReport = $this->hasMany('App\CreditReport','application_id','id');
        if(static::$isAccountOpened){
            $creditReport->where('applicant_type',1);
        }
        return $creditReport;
    }

    public function scopeWhere($query, $column, $value){
        return in_array($column, $this->encryptable) ? $query->where($column, wall_encrypt($value)) : $query->where($column, $value);
    }

    public function logs(){
        return $this->hasMany('App\StatusLogs','application_id','id');
    }

    public function disbursed(){
        return $this->hasOne('App\StatusLogs','application_id','id')->where('status','disbursed')->orderBy('created_at','desc');
    }

    public function cancelled(){
        return $this->hasOne('App\StatusLogs','application_id','id')->whereIn('status', ['cancelled','cancellation in-process'])->orderBy('created_at','desc');
    }

    public function closed(){
        return $this->hasOne('App\StatusLogs','application_id','id')->where('status','closed')->orderBy('created_at','desc');
    }

    public function rejected(){
        return $this->hasOne('App\StatusLogs','application_id','id')->where('status','rejected')->orderBy('created_at','desc');
    }

    public function aborted(){
        return $this->hasOne('App\StatusLogs','application_id','id')->where('status','aborted')->orderBy('created_at','desc');
    }

    public function approved(){
        return $this->hasOne('App\StatusLogs','application_id','id')->where('status','approved')->orderBy('created_at','desc');
    }

    public function verificationChecklist(){
        return $this->hasone('App\checklist','consumer_application_id','id');
    }

    public function foir(){
        $foir = $this->hasMany('App\FOIR','application_id','id');
        if(static::$isAccountOpened){
            $foir->where('isOpened',1);
        }
        if(static::$isCFFoirNotInclude){
            $foir->where('AccountType','!=','Credit Fair EMI');
        }
        $foir = $foir->select(['id','application_id','credit_id','AccountType','ApprovedAmount','Balance','InterestRate','RepaymentTenure','InstallmentAmount','cc_loan','DateOpened','applicant_type', 'isOpened', 'LastPaymentDate', 'dpd', 'DateClosed','OwnershipType','created_by','PastDueAmount','LastPayment','ReportedDate', 'is_close_date_updated','reason_info', 'created_at'])->orderBy('applicant_type','asc');
        return $foir;
    }

    public function documents(){
        return  $this->hasMany('App\ConsumerApplicationFiles','consumer_application_id','id');
    }

    public function disbursement_requests(){
        return $this->hasMany('App\DisbursementRequests', 'application_id', 'id')->where('is_disbursed', false);
    }

    public function equifax_documents(){
        return  $this->hasOne('App\ConsumerApplicationFiles','consumer_application_id','id')->where('file_type','equifax_report')->where('applicant_type', 1)->orderBy('created_at', 'DESC');
    }

    public function coapp_equifax_documents(){
        return  $this->hasOne('App\ConsumerApplicationFiles','consumer_application_id','id')->where('file_type','co_applicant_equifax_report')->where('applicant_type', 2)->orderBy('created_at', 'DESC');
    }

    public function electricity_bill(){
        return  $this->hasOne('App\ConsumerApplicationFiles','consumer_application_id','id')->where('file_type','electricity_bill')->where('applicant_type', 1)->orderBy('created_at', 'DESC');
    }

    /*public function disbursementAdvice(){
        return  $this->hasOne('App\ConsumerApplicationFiles','consumer_application_id','id')->where('file_type','pro_forma_invoice')->orderBy('created_at','desc');
    }*/

    public function company(){
        return $this->hasOne('App\Company','id','company_name');
    }

    public function co_applicant_company(){
        return $this->hasOne('App\Company','id','co_applicant_company_name');
    }

    public function application_element(){
        $application_element = $this->hasOne('App\ConsumerApplicationElement','application_id','id');
        if(static::$center_id > 0){
            $application_element = $application_element->where('center_id','=',static::$center_id);
        }
        return $application_element;
    }

    public function user(){
        return $this->hasOne('App\User','id','user_id');
    }

    public function application_additional(){
        return $this->hasOne('App\ConsumerApplicationAdditional','application_id','id');
    }

    public function advisor(){
        return $this->hasOne('App\User','id','created_by');
    }
    public function activeOffer(){
        return $this->hasOne('App\MerchantOffers','id','offer_id');
    }
    public function Checklist(){
        return $this->hasOne('App\Checklist','application_id','id');
    }
    public function lender(){
        return $this->hasOne('App\Lenders','id','lender_id');
    }
    public function digital_sign(){
        $application_element = $this->hasMany('App\DigitalSignDetails','application_id','id');
        if(static::$isApplicantType){
            $application_element = $application_element->where('type','=','consumer');
        }
        return $application_element;
    }

    public function invoice(){
        $invoice =  $this->hasOne('App\Invoices','application_id','id');
        if(static::$isSubventionInvoice){
            $invoice = $invoice->where('type', 'subvention_invoice');
        }else{
            $invoice = $invoice->where('type', 'processing_invoice');
        }
        return $invoice;
    }

    public function invoices(){
        return $this->hasMany('App\Invoices','application_id','id');
    }

    public function co_applicant_logs(){
        return $this->hasMany('App\CoApplicateValidationLog','application_id','id');
    }

    public function comments(){
        return $this->hasMany('App\Comments','application_id','id')->where('type','consumer')->orderBy('created_at','DESC');
    }

    public function merchant_comment(){
        return $this->hasOne('App\Comments','application_id','id')->where('show_merchant','=',1)->where('type','consumer')
            ->orderBy('created_at','DESC')->limit(1);
    }

    public function comment(){
        return $this->hasMany('App\Comments','application_id','id')
            ->orderBy('created_at','DESC')->limit(1);
    }

    public function application_rating(){
        return $this->hasOne('App\Rating','application_id','id');
    }

    public function hypothecation_logs(){
        return $this->hasMany('App\Hypothecation','application_id','id');
    }

    public function calls(){
        return $this->hasMany('App\CallLogs','_id','id')->where('id_type','application_id')->where(function ($query) {
            $query->whereNull('status')
                ->orWhereIn('status', ['in-progress','ringing']);
        });
    }

    public function totalCalls(){
        return $this->hasMany('App\CallLogs','_id','id')->where('id_type','application_id');
    }

    public function approval(){
        return $this->hasOne('App\Approval','application_id','id');
    }

    public function highest_dpd(){
        return $this->hasOne('App\EmiPayment','application_id','id')->where('payment_status','!=','success')->orderBy('delay_days','desc');
    }

    public function emi_payment()
    {
        $emi_payment  = $this->hasMany('App\EmiPayment','application_id','id')->orderBy('emi_date','asc');
        if(static::$emi_date){
            $emi_payment = $emi_payment->where('emi_date', static::$emi_date);
        }
        return $emi_payment;
    }

    public function payment_transaction()
    {
        $payment_transaction  = $this->hasMany('App\PaymentTransaction','application_id','id')->orderBy('payment_reconciliation_date','asc');
        return $payment_transaction;
    }

    public function foreclosed_transaction()
    {
        return $this->hasOne('App\PaymentTransaction','application_id','id')->where('payment_for', 'Foreclosure')->orderBy('payment_reconciliation_date','desc');
    }

    public function foreclosure_breakup()
    {
        return $this->hasOne('App\ForeclosureBreakup','application_id','id')->whereNull('deleted_at')->orderBy('created_at', 'desc');
    }

    public function writeoff_transaction()
    {
        return $this->hasOne('App\PaymentTransaction','application_id','id')->where('payment_for', 'Write-off')->orderBy('payment_reconciliation_date','desc');
    }

    public function settlement_payment()
    {
        return $this->hasMany('App\PaymentTransaction', 'application_id', 'id')
            ->whereIn('payment_for', [
                'settled_principal',
                'settled_interest',
                'settled_bounce',
                'settled_penal'
            ])
            ->orderBy('created_at', 'desc');
    }
    
    public function last_payment_date()
    {
        $last_payment_date  = $this->hasOne('App\PaymentTransaction','application_id','id')->where('status','success')->orderBy('created_at','desc');
        return $last_payment_date;
    }

    public function telecom_data()
    {
        return $this->hasOne('App\TelecomData','mobile_number','mobile_number')->orderBy('id');
    }
    public function offer(){
        return $this->hasOne('App\MerchantOffers','id','offer_id');
    }

    public function saveCustomer($d = array()){
        if($d){
            $this->attributes = $d;
        }
        $apiController = new ApiController();
        $customer = new \stdClass();
        $c_applicant_id = 0;
        $c_co_applicant_id = 0;
        if($applicant_id = $this->getIdFromExisting($apiController->isExistingCustomer(new Request($this->attributes)))){
            if (is_bool($applicant_id)) {
                $applicant = new Customers();
                $attributes = $this->attributes;
                $attributes['gender'] = isset($this->attributes['gender']) ? (($this->attributes['gender'] == 'FEMALE') ? 1 : 2) : null;
                $applicant->fill($attributes)->save();
            }
            $c_applicant_id = isset($applicant->id) ? $applicant->id : $applicant_id;
        }

        if(isset($this->attributes['co_applicant_name']) && !empty($this->attributes['co_applicant_name']) && $applicant_id = $this->getIdFromExisting($apiController->isExistingCustomer(new Request([
            'pan_card' => $this->attributes['co_applicant_pan_card'],
            'mobile_number' => $this->attributes['co_applicant_mobile_number'],
            'email' => $this->attributes['co_applicant_email'],
        ])))){
            if (is_bool($applicant_id)){
                $co_applicant = new Customers();
                $co_app_gender = isset($this->attributes['co_applicant_gender']) ? (($this->attributes['co_applicant_gender'] == 'FEMALE') ? 1 : 2) : null;
                $co_applicant->fill([
                    'name' => $this->attributes['co_applicant_name'],
                    'email' => $this->attributes['co_applicant_email'],
                    'mobile_number' => $this->attributes['co_applicant_mobile_number'],
                    'gender' => $co_app_gender,
                    'pan_card' => $this->attributes['co_applicant_pan_card'],
                    'aadhaar_card' => $this->attributes['co_applicant_aadhaar_card'],
                    'dob' => $this->attributes['co_applicant_dob'],
                ])->save();
            }
            $c_co_applicant_id = isset($co_applicant->id) ? $co_applicant->id : $applicant_id;
        }
        $customer->applicant_id = $c_applicant_id;
        $customer->co_applicant_id = $c_co_applicant_id;
        return $customer;
    }

    public function getIdFromExisting($existingCustomers){
        $applicant_id = true;
        $existingCustomers = $existingCustomers->getData();
        if ($existingCustomers){
            foreach ($existingCustomers->data as $existingCustomer){
                if ($existingCustomer->applicant_id && $applicant_id == true){
                    $applicant_id = $existingCustomer->applicant_id;
                    break;
                }
            }
        }
        return $applicant_id;
    }

    public function activeMerchant(){
        return $this->hasOne('App\Merchant','id','merchant_id')->where('status','active')->where('is_guest_active',1);
    }

    public function abflUTR(){
        return $this->hasMany('App\ABFLUTRUpdate','account_id','id');
    }

    public function getAgeAttribute()
    {
        return Carbon::parse($this->attributes['dob'])->age;
    }

    public function getNameSplitAttribute($type = 1, $name = '')
    {
        $custName = $type == 1 ?( $this->attributes['name'] ?? '') : ($this->attributes['co_applicant_name'] ?? '');
        $custName = empty($custName) ? $name : $custName;
        $firstName = ''; $middleName = ''; $lastName = '';
        $nameSplit = explode(' ', $custName);
        if ($nameSplit > 1){
            $firstName = $nameSplit[0];
            if (!isset($nameSplit[2]) && isset($nameSplit[1])){
                $lastName = $nameSplit[1];
            }
            if (isset($nameSplit[2])){
                $middleName = $nameSplit[1];
                unset($nameSplit[0], $nameSplit[1]);
                $lastName = implode(' ', $nameSplit);
            }
        }

        return ['firstName' => $firstName, 'middleName' => $middleName, 'lastName' => $lastName];
    }

    public function getAddressSplitAttribute($type = 1, $address = '')
    {
        $addrLine = [];
        $addressL1 = '';

        if (!empty($address)) {
            $ds = explode(' ', trim($address));
            $lineLength = 0;

            foreach ($ds as $ads) {
                if ($lineLength + strlen($ads) + 1 <= 60) {
                    $addressL1 .= $ads . ' ';
                    $lineLength += strlen($ads) + 1;
                } else {
                    $addrLine[] = trim($addressL1);
                    $addressL1 = $ads . ' ';
                    $lineLength = strlen($ads) + 1;
                }
            }

            // Add the last line
            if (!empty($addressL1)) {
                $addrLine[] = trim($addressL1);
            }

            $addrLine1 = $addrLine[0] ?? '';
            $addrLine2 = $addrLine[1] ?? '';
            $addrLine3 = ($addrLine[2] ?? '').' '.($addrLine[3] ?? '');
        }

        return ['address_1' => trim($addrLine1 ?? ''), 'address_2' => trim($addrLine2 ?? ''), 'address_3' => trim($addrLine3 ?? '')];
    }

    public function cancellation(){
        return $this->hasMany('App\CancellationDisbursement','merchant_id','merchant_id')->whereNull('adjusted_to')->select('id','application_id','merchant_id','cancellation_interest_charges','cancellation_fixed_charges','total_amount_adjusted','adjusted_by');
    }

    public function disbursement(){
        return $this->hasMany('App\Disbursement','application_id','id')->where('adjusted_amount','>', 0);
    }

    public function disbursementV1(){
        return $this->hasOne('App\Disbursement','application_id','id')->orderBy('created_at', 'desc');
    }

    public function pendingAdjustableAmount(){
        return $this->hasMany('App\PendingBalance','merchant_id','merchant_id')->where('status','pending')->where('pending','>',0)->where('adjusted_to',0);
    }

    public function userGeolocation(){
        return $this->hasOne('App\UserGeolocation','_id','id')->where('service','cpv')->whereNull('deleted_at')->where('id_type','application_id');
    }
    public function finBitData(){
        return $this->hasOne('App\FinBitData','application_id','id');
    }

    public function payoutStatus(){
        return $this->hasOne('App\PayoutStatus','application_id','id');
    }

    public function CFPayoutDirectTransfer(){
        return $this->hasOne('App\CFPayoutDirectTransfer','application_id','id')->orderBy('created_at','desc');
    }

    public function CFPayoutRequestTransferStatus(){
        return $this->hasMany('App\CFPayoutRequestTransferStatus','application_id','id')->orderBy('created_at','desc');
    }

    public function avanseUTRStatus(){
        return $this->hasOne('App\AvanseDisbursementStatus','application_id','id')->orderBy('created_at','desc');
    }

    public function avanseMandateStatus(){
        return $this->hasOne('App\AvanseMandate','application_id','id')->orderBy('created_at','desc');
    }

    public function moratorium(){
        return $this->hasOne('App\Moratorium','application_id','id')->where('status',1)->orderBy('emi_date','asc');
    }

    public function moratoriums(){
        return $this->hasMany('App\Moratorium','application_id','id')->where('status',1)->orderBy('emi_date','asc');
    }

    public function moratoriumEMIPayment(){
        return $this->hasOne('App\Moratorium','application_id','id')->where('status',1)->orderBy('emi_date','asc');
    }

    public function principal_outstanding(){
        return $this->hasOne('App\PrincipalOutstanding','application_id','id')->orderBy('date','desc');
    }

    public function ApproverData(){
        return $this->hasOne('App\ApproverData','application_id','id');
    }

    public function trade_advance(){
        return $this->hasOne('App\TradeAdvanceDisbursement','application_id','id');
    }

    public function products(){
        return $this->hasMany('App\Products','merchant_id','merchant_id')->withTrashed();
    }

    public function logger(){
        return $this->hasMany('App\ContentLogger','application_id','id')->whereNotIn('status', array('form completed', 'incomplete form', 'rejected', 'aborted', 'in-process', 'waiting for documents', 'waiting for decision', 'pre approved'));
    }

    public function all_logger(){
        return $this->hasMany('App\ContentLogger','application_id','id');
    }

    public function DisbursementOffersData(){
        return $this->hasMany('App\DisbursementOffersData','offer_id','offer_id');
    }

    public function disbursementOfferDisbursed(){
        return $this->hasMany('App\DisbursementOffers','application_id','id')->whereNull('deleted_at');
    }

    public function gst_pan_data(){
        return $this->hasOne('App\GSTPANData','application_id','id');
    }

    public function epf_uan_lookup(){
        return $this->hasOne('App\EPFUANLookup','application_id','id');
    }

    public function devices(){
        return $this->hasMany('App\Devices','user_id','user_id');
    }

    public function isAvanse() {
        return ($this->lender_id === self::AVANSE_LENDER_ID) ? true : false;
    }

    public function isLendBox() {
        return ($this->lender_id === LendBox::$lender_id) ? true : false;
    }

    public function isLendBoxLSP() {
        return ($this->lender_id === LendBoxLSP::$lender_id) ? true : false;
    }

    public function isKMGP2P() {
        return ($this->lender_id === KMGP2P::$lender_id) ? true : false;
    }

    public function finBitDataBorrower(){
        return $this->hasOne('App\FinBitData','application_id','id')->where('applicant_type',1);
    }

    public function finBitDataCoBorrower(){
        return $this->hasOne('App\FinBitData','application_id','id')->where('applicant_type',2);
    }

    public function avanse(){
        return $this->hasOne('App\AvanseCreateCustomer','application_id','id');
    }

    public function coAvanse(){
        return $this->hasOne('App\AvanseCreateCustomer','application_id','id');
    }

    public function avanseDisbursed(){
        return $this->hasOne('App\AvanseDisbursement','application_id','id');
    }

    public function avanseByApplicant(){
        return $this->hasOne('App\AvanseCreateCustomer','applicant_id','applicant_id');
    }

    public function avanseByCoApplicant(){
        return $this->hasOne('App\AvanseCreateCustomer','applicant_id','applicant_id');
    }

    public function disbursement_log(){
        return  $this->hasMany('App\DisbursementLogs','application_id','id');
    }

    public function liability_log(){
        return $this->hasOne('App\LiabilityLog','application_id','id');
    }

    public function ConsumerApplicationElement(){
        return $this->hasOne('App\ConsumerApplicationElement','application_id','id');
    }

    public function cibilReportBorrower(){
        return $this->hasMany('App\CibilBureau','application_id','id')->where('applicant_type', 1);
    }

    public function cibilReportCoBorrower(){
        return $this->hasMany('App\CibilBureau','application_id','id')->where('applicant_type', 2);
    }

    public function agency(){
        return $this->hasOne('App\AgencyApplication','application_id','id')->whereNull('deleted_at');
    }

    public function digioLoanAgreement(){
        return $this->hasOne('App\Model\LoanAgreementVendor','application_id','id')->whereNull('deleted_at')->where('status','com');
    }
    public function kycdetails(){
        return $this->hasOne('App\KYCDetails','application_id','id')->whereNull('deleted_at');
    }
    public function co_kycdetails(){
        return $this->hasOne('App\KYCDetails','application_id','co_applicant_id')->whereNull('deleted_at');
    }

    public static function postVkycAction($id) {
        $appObj = self::where('id', $id)->first();
        switch ($appObj->lender_id) {
            // for avanse lender run the login here
            case 3:
                $aa = $coaa = false;
                // check if applicant has been approved
                if (!empty($appObj->pan_card)) {
                    if(ConsumerApplicationController::VKYC_VENDOR == "karza") {
                        $aa = self::checkKarzaApproved($appObj->id, 1);
                    }else {
                        $aa = self::checkHypervergeApproved($appObj->id, 1);
                    }
                }

                // check if co-applicant has been approved
                if (!empty($appObj->co_applicant_pan_card)) {
                    if(ConsumerApplicationController::VKYC_VENDOR == "karza") {
                        $coaa = self::checkKarzaApproved($appObj->id, 2);
                    }else {
                        $coaa = self::checkHypervergeApproved($appObj->id, 2);
                    }
                } else { // no co-applicant on the application
                    $coaa = true;
                }
                //return "Applicant VKYC ".(($aa === true) ? "approved" : "unapproved")." Co-spplicant VKYC ".(($coaa === true) ? "approved" : "unapproved");
                // applicant and/or co-applicant has been approved
                if ($aa === true && $coaa === true) {
                    //@info: we make up this request to work on updateStatusFromJob function
                    //request()->merge(['status' => $appObj->state,'previous_state' => 'cf approved', 'state' => 'cf approved']);
                    $cacObj = new ConsumerApplicationController();
                    $cacObj->initiateForLatestBankStatement($appObj->id);
                    $cacObj->saveLiabilityPercent($appObj, $appObj->id, 'job');
                    $cacObj->checkApprovedPinCode($appObj->id);
                    $cacObj->ApprovalInit($appObj, $appObj->id);
                    $cacObj->disbursementOffers($appObj->id);
                    $cacObj->sendemandate($appObj->id);
                    $cacObj->sendSanctionLetter($appObj->id);
                    $cacObj->proformaSigningNotification($appObj->id);
                    $cacObj->creditLimitNotification($appObj->id);
                    $cacObj->insertIntoJob($appObj->id, 'referral_communication', 'approved');
                    $cacObj->whatsAppCommunication($appObj, 'approved');
                    unset($cacObj);
                }
                return "Applicant VKYC ".(($aa === true) ? "approved" : "unapproved")." Co-applicant VKYC ".(($coaa === true) ? "approved" : "unapproved");
                break;
            default:
                break;
        }
    }

    public static function checkKarzaApproved($applicant_id, $applicant_type) {
        $status = false;
        $hwObj = KarzaVideoWebhook::where('application_id', $applicant_id)
                ->where('applicant_type', $applicant_type)->first();
        if (!empty($hwObj) && !empty($hwObj->data)) {
            $vkycStatus = json_decode($hwObj->data, 1);
            if(!empty($vkycStatus['approvedByAgent']) && strtolower($vkycStatus['approvedByAgent']) === 'accepted') {
                $status = true;
            }
        }
        unset($hwObj);
        return $status;
    }

    public static function checkHypervergeApproved($applicant_id, $applicant_type) {
        $status = false;
        $hwObj = HypervergeWebhook::where('event_type', 'vcip_kyc_status')
                ->where('application_id', $applicant_id)
                ->where('applicant_type', $applicant_type)->first();
        if (!empty($hwObj) && !empty($hwObj->data)) {
            $vkycStatus = json_decode($hwObj->data, 1);
            if(!empty($vkycStatus['status']) && strtolower($vkycStatus['status']) === 'approved') {
                $status = true;
            }
        }
        unset($hwObj);
        return $status;
    }

    public static function postCreateCustomerAction($id) {
        $appObj = self::where('id', $id)->first();
        if (!empty($appObj)) {
            switch ($appObj->lender_id) {
                case 3: // avanse lender
                    return CreateCustomer::postCreateActions($appObj);
                    break;
                default:
                    return true;
                    break;
            }
        }
        return "Invalid loan id";

    }

    public static function postCreateFinanceAction($id) {
        $appObj = self::where('id', $id)->first();
        if (!empty($appObj)) {
            switch ($appObj->lender_id) {
                case 3: // avanse lender
                    return CreateFinance::postCreateActions($appObj);
                    break;
                default:
                    return true;
                    break;
            }
        }
        return "Invalid loan id";

    }

    public static function postDisbursementInstructionAction($id) {
        $appObj = self::where('id', $id)->first();
        if (!empty($appObj)) {
            switch ($appObj->lender_id) {
                case 3: // avanse lender
                    return AvanseDisbursementInstruction::postDisbursementInstructionActions($appObj);
                    break;
                default:
                    return true;
                    break;
            }
        }
        return "Invalid loan id";

    }

    public static function postFormCompleted($id) {
        $appObj = self::where('id', $id)->first();
        if (!empty($appObj)) {
            // call markytics api here
            $obj = Prediction::apiCustomerResponse($appObj);
            if ($obj instanceof Prediction) {
                return $obj->pid;
            }
            return $obj;
        }
        return "Invalid loan id";
    }

    public static function postBureauPull($id) {
        $appObj = self::where('id', $id)->first();
        if (!empty($appObj)) {
            $creditReport = CreditReport::where('application_id', $id)->first(['id']);
            if(isset($creditReport->id)) {
                // call markytics api here
                $obj = Prediction::apiBureauResponse($appObj);
                if ($obj instanceof Prediction) {
                    $returnId = 0;
                    if(isset($obj->id)){
                        $returnId = $obj->id;
                    } elseif(isset($obj->pif)){
                        $returnId = $obj->pif;
                    }
                    return $returnId;
                }
                return $obj;
            }
        }
        return "Invalid loan id";
    }

    public static function postCSBureauBankPull($id) {
        $appObj = self::where('id', $id)->first();
        if (!empty($appObj)) {
            // call markytics api here
            $obj = Prediction::apiCSBureauBankResponse($appObj);
            if ($obj instanceof Prediction) {
                return $obj->pid;
            }
            return $obj;
        }
        return "Invalid loan id";
    }

    public function AvanseNoc(){
        return $this->hasOne('App\AvanseNoc','application_id','id')->whereIn('execution_status',['pending','failed'])->where('is_available',1);
    }

    public function approved_pincode()
    {
        return $this->hasOne('App\ApprovedPincodeLists','pin_codes','current_address_pincode');
    }

    public function lender_bank(){
        return $this->hasOne('App\LenderBank','id','lender_id');
    }

    public function application_emi_details(){
        return $this->hasOne('App\ApplicationEMIDetails', 'application_id', 'id');
    }

    public function avanse_access(){
        $application_element = $this->hasOne('App\ConsumerApplicationElement','application_id','id');
        $application_element = $application_element->where('unique_id_number',static::$uniqueRefId);
        return $application_element;
    }
}
