<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

use App\ConsumerApplication;
use App\Http\Controllers\Admin\ConsumerDocument;
use App\ekycIntegration;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class LoanAgreementVendor extends Model
{
	use SoftDeletes;

    protected $table = 'loan_agreement_vendor';

    public static function addEntry($loanAppObj, $vendor, $output = []) {
//        $existing_requests = self::where('application_id', $loanAppObj['id'])->orderBy('created_at', 'desc');
//        if($existing_requests->first()){
//            $existing_requests->delete();
//        }
		if(!empty($loanAppObj) && !empty($loanAppObj['id']) && !empty($loanAppObj['lender_id'])) {
			//if(false === ($obj = self::checkIfEntryExist($loanAppObj['id']))) {
			$obj = new self();
	    	$obj->application_id = $loanAppObj['id'];
			//}
			$obj->esign_vendor = $vendor;
			switch($vendor) {
				case 'digio':
					$obj->vendor_doc_id = !empty($output['id']) ? $output['id'] : '';
					if (!empty($output['signing_parties'][0]['signature_type'])) {
						if ($output['self_sign_type'] === 'aadhaar') {
							$obj->esign_type =  'adh';
						} else if ($output['self_sign_type'] === 'electronic') {
							$obj->esign_type =  'otp';
						} else if ($output['self_sign_type'] === 'dsc') {
							$obj->esign_type =  'dsc';
						}
					}
					if (!empty($output['agreement_status'])) {
						if ($output['agreement_status'] === 'requested') {
							$obj->status =  'pen';
						} else if ($output['agreement_status'] === 'completed') {
							$obj->status =  'com';
						} else if ($output['agreement_status'] === 'expired') {
							$obj->status =  'exp';
						}
					}
					if (!empty($loanAppObj['co_applicant_name'])) {
						$obj->is_cobor = 1;
					}
					$obj->is_stamped = (_env('ESTAMP_DIGIO', 0)); // all avanse agreement needs a stamp
					$obj->stamp_tag = (_env('ESTAMP_DIGIO_TAG_NAME', '')); // all stamps are identified by tags in digio platform
					$obj->stamp_qty = 1; // default quantity
					$obj->expiry_days = 30; // default expiry date of a loan agreement
					break;
			}
			$obj->response = json_encode($output);
	    	$obj->save();
	    	return $obj;
	    }
	    return false;
    }

    public static function checkIfEntryExist($app_id) {
    	$obj = self::where('application_id', $app_id)->first();
    	if(!empty($obj)) {
    		return $obj;
    	}
    	return false;
    }

    public static function checkIfEntryExistByDocNApp($app_id, $doc_id) {
    	$obj = self::where('application_id', $app_id)->where('vendor_doc_id', $doc_id)->first();
    	if(!empty($obj)) {
    		return $obj;
    	}
    	return false;
    }

    public function checkIfSignDone() {
    	if ($this->status === 'com') {
			return true;
		}
    	return false;
    }

    public function checkIfSignExpired() {
    	if ($this->status === 'exp') {
    		return true;
    	}
    	return false;
    }

    public static function getLastEntry($id) {
    	$obj = self::where('application_id', $id)->orderBy('created_at', 'desc')->first();
    	if(!empty($obj)) {
    		return $obj;
    	}
    	return false;
    }

    public function checkIfStillPending() {
    	if ($this->status === 'pen') {
			return true;
		}
		return false;
    }

    public static function sendLoanAgreementToVendor($vendor, $appObj, $stype) {

    	$cDocObj =  new ConsumerDocument(new Request([]));
        $agreement =  $cDocObj->getSanctionLetterAndLoanAgreement($appObj['id']);
        //\Log::info($agreement);
        if (!empty($agreement['pdf']) && !empty($agreement['fileName'])) {
            $str = Storage::disk('storage');
			// $file = $agreement['isInsurance'] ? $agreement['pdf'] : $agreement['pdf']->output();
            $file = $agreement['pdf']->output();
            $str->put($agreement['fileName'], $file);
            if ($str->exists($agreement['fileName'])) {
                $signers = [];
                if (!empty($appObj['name']) && !empty($appObj['email'])) {
                    $signers [] = [
                        "identifier" => $appObj['email'],
                        "name" => $appObj['name'],
                        "sign_type" => $stype,
                        "reason" => "Loan agreement e-sign borrower"
                    ];
                }
                if (!empty($appObj['co_applicant_name']) && !empty($appObj['co_applicant_email'])) {
                    $signers [] = [
                        "identifier" => $appObj['co_applicant_email'],
                        "name" => $appObj['co_applicant_name'],
                        "sign_type" => $stype,
                        "reason" => "Loan agreement e-sign co-borrower"
                    ];
                }
                $kycObj = new ekycIntegration();
                $output = $kycObj->uploadEsignDocument($signers, $agreement['fileName'], 'storage', (_env('ESTAMP_DIGIO', 0)), (_env('ESTAMP_DIGIO_TAG_NAME', '')), 1, $appObj['id']);
                // return $output;
                 //$output = json_decode('{"id":"DID210531193816408VA577GFGC1O2SL","is_agreement":true,"agreement_type":"outbound","agreement_status":"requested","file_name":"Unsigned-Loan-Agreement-5329.pdf","created_at":"2021-05-31 19:38:17","self_signed":false,"self_sign_type":"aadhaar","no_of_pages":10,"signing_parties":[{"name":"ShortIO test","status":"requested","type":"self","signature_type":"aadhaar","identifier":"dinesh@creditfair.in","reason":"Loan agreement e-sign borrower","expire_on":"2021-06-30 23:59:59","sign_coordinates":[{"signing_party_id":"SPI210531193818660ERFZCTQKX3R6UD","page_no":10,"llx":455,"lly":60,"urx":595,"ury":20}]}],"sign_request_details":{"name":"Credit Fair","requested_on":"2021-05-31 19:38:18","expire_on":"2021-06-30 23:59:59","identifier":"devteam@creditfair.in","requester_type":"org"},"channel":"api","other_doc_details":[]}', 1);
                //\Log::info($output);
                if (is_array($output) && !empty($output['id'])) {
                    $resp = self::addEntry($appObj, 'digio', $output);
                    if(false !== $resp) {
                        return ['id' => !empty($resp->id) ? $resp->id : '',
                        'doc_id' => !empty($resp->vendor_doc_id) ? $resp->vendor_doc_id : ''];
                    } else {
                        throw new \Exception("Something went wrong while saving digio e-sign api reposne for application ".$appObj['id']);
                    }
                } else {
                    throw new \Exception("Something went wrong while calling digio e-sign api for application ".$appObj['id']. " ".json_encode($output));
                }

            } else {
                throw new \Exception("Agreement PDF not found at location for application ".$appObj['id'], 1);
            }
        } else {
            throw new \Exception("Agreement PDF not found for application ".$appObj['id'], 1);
        }
    }

    public function agreementSignedUpdate($signed_by, $txn_id) {

    	if ($signed_by === 'b' || $signed_by === 'cb') {
    		if ($signed_by === 'b') {
	    		$this->is_bor_signed = 1;
	    		$this->bor_signed_id = $txn_id;
	    	} elseif ($signed_by === 'cb' && $this->is_cobor === 1) {
	    		$this->is_cobor_signed = 1;
	    		$this->cobor_signed_id = $txn_id;
	    	}
	    	$this->save();
			return $this;
    	}
    	return false;
    }

    public function checkIfSigningPending() {
    	$ret = [];
    	if($this->is_bor_signed === 0) {
    		$ret[] = ['b'];
    	}
    	if($this->is_cobor === 1 && $this->is_cobor_signed === 0) {
			$ret[] = ['cb'];
		}
		return $ret;
    }

    public function markCompleted() {
    	$this->status = 'com';
    	$this->save();
    	return $this;
    }


    public function downloadAgreement($mark_com = 1) {

    	$kycObj = new ekycIntegration();
        $resp = $kycObj->downloadEsignDocument($this->vendor_doc_id, $this->application_id);
    	if($resp) {
    		//$file_name = 'Signed-Loan-Agreement-'.$this->application_id;
    		(new ConsumerDocument(new Request()))->uploadToS3('loan_agreement_esign', $this->application_id, $resp);
    		if ($mark_com === 1) {
    			$this->markCompleted();
    			$this->downloadAgreementDetails();
    		}
    		return true;
    	}
        return false;
    }

    public function downloadAgreementDetails() {
    	$kycObj = new ekycIntegration();
        $resp = $kycObj->downloadDocumentDetails($this->vendor_doc_id, $this->application_id);
    	if($resp) {
    		$this->response = json_encode($resp);
    		$this->save();
            unset($kycObj);
    		return $this;
    	}
        return false;
    }
}
