<?php

namespace App\Method\Homeville\Payload;

use App\APIWrapper\Wrapper;
use App\Company;
use App\ConsumerApplication;
use App\ConsumerApplicationElement;
use App\ConsumerApplicationFiles;
use App\HomevilleDocument;
use App\HomevilleLoans;
use App\Http\Controllers\Admin\ConsumerApplicationController;
use App\Http\Controllers\Admin\DisbursementController;
use App\Http\Controllers\Grade\GradeController;
use App\LoanHypothecation\LoanHypothecation;
use App\Merchant;
use App\Method\Homeville\Helpers\HomevilleHelper;
use App\Method\Homeville\HomevilleMethods;
use App\PaymentTransaction;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

class Payload implements HomevilleHelper
{

    public $solar = 24;
    public $home_decore = 22;

    public $request;
    public $error = null;
    public $additional_data = [];
    private $is_update = false;

    public function addPayload(Request $request){
        $this->request = $request;
    }

    public function getPayload($func){
        if(method_exists($this, $func)){
            return ['payload' => $this->$func(), 'additional_data' => $this->additional_data];
        }
        return ['payload' => []];
    }

    public function createApplication($wrapper = null)
    {
        $this->initApplicationData();
        if ($this->error){
            return $this;
        }

        $data = [
            "loan_type" => $this->request->get('category_type'),
            "loan_subcategory" => $this->request->get('loan_subcategory'),
            "loan_purpose" => $this->request->get('loan_purpose'),
            "loan_amount" => $this->request->get('loan_amount'),
            "tenure_months" => $this->request->get('loan_tenure'),
            "market_value" => $this->request->get('market_value'),
            "push_to_partner" => "",
            "ahfc_sec_ref" => $this->request->get('loan_application_no'),
            "ahfc_pri_ref" => $this->request->get('id'),
            "bt_details" => $this->getBTDetails(),
            "applicants" => $this->getApplicants(),
            //"family_details" => $this->getFamilyDetails(),
            //"references" => $this->getReferences(),
            "guarantors" => $this->getGuarantors()
        ];

        if ($this->is_update) {
            $data['case_id'] = $this->request->get('case_id');
            $data['bank_details'] = $this->getBankDetails();
        }
        return $data;
    }


    public function updateApplication($wrapper = null){
        $this->is_update = true;
        return $this->createApplication();
    }

    private function getGuarantors(){
        return [];
        return [
            [
                "ahfc_ref_id" => "",
                "applicant_type" => "",
                "applicant_subtype" => "",
                "first_name" => "",
                "last_name" => "",
                "mobile" => "",
                "email" => "",
                "pan" => "",
                "has_form_60" => "",
                "aadhar_number" => "",
                "dob" => "",
                "qualification" => 0,
                "gender" => "",
                "marital_status" => "",
                "income_consideration" => true,
                "father_name" => "",
                "citizenship" => "",
                "ca_line1" => "",
                "ca_line2" => "",
                "ca_pincode" => "",
                "ca_residence_type" => "",
                "ca_residence_duration" => 0,
                "ca_city" => 0,
                "ca_state" => 0,
                "pa_line1" => "",
                "pa_line2" => "",
                "pa_city" => 0,
                "pa_state" => 0,
                "pa_pincode" => "",
                "pa_residence_type" => "",
                "pa_residence_duration" => "",
                "pp_industry" => "",
                "pp_employment_type" => "",
                "pp_city" => 0,
                "pp_pincode" => "",
                "pp_org_address_line1" => "",
                "pp_org_address_line2" => "",
                "pp_state" => 0,
                "pp_designation" => "",
                "pp_current_exp_months" => 0,
                "pp_salaried_type" => "",
                "pp_gross_salary" => 0,
                "pp_total_experience_months" => 0,
                "mother_maiden_name" => "",
                "spouse_name" => "",
                "community" => "",
                "religion" => "",
                "alt_mobile" => "",
                "pp_company_name" => "",
                "pp_business_since" => "",
                "pp_net_salary" => "",
                "pp_other_income" => "",
                "applicant_id" => 0
            ]
        ];
    }

    private function getReferences(){
        return [
            [
                "reference_name" => $this->request->get('reference_name_1'),
                "mobile_no" => $this->request->get('reference_contact_1'),
                "occupation" => "",
                "years_known" => "",
                "pincode" => "",
                "address" => "",
                "relation" => "",
                "reference_detail_id" => 0
            ]
        ];
    }

    private function getFamilyDetails(){
        return [
            [
                "first_name" => "",
                "last_name" => "",
                "age" => "",
                "relationship" => "brother, sister, mother, father, other.",
                "monthly_income" => 0,
                "occupation" => "",
                "family_detail_id" => 0
            ]
        ];
    }

    private function getBankDetails(){
        if ($this->request->get('bank_id') && isset($this->request->get('bank_details')->name)) {
            return [
                [
                    "bank_id" => $this->request->get('bank_id'),
                    "account_holder_name" => $this->request->get('bank_details')->name,
                    "account_number" => $this->request->get('bank_details')->account_number,
                    "confirm_account_number" => $this->request->get('bank_details')->account_number,
                    "ifsc" => $this->request->get('bank_details')->ifsc_code,
                    "account_type" => $this->request->get('bank_details')->account_type,
                    "branch_name" => $this->request->get('bank_details')->branch_name,
                    "bank_detail_id" => $this->request->has('bank_detail_id') ? $this->request->get('bank_detail_id') : 0,
                    "belongs_to" => "self",
                    "category" => ""
                ]
            ];
        }else{
            return [];
        }
    }

    private function getApplicants(){

        $applicants = [];

        if ($this->request->get('first_name')){
            $applicants[] = [
                "ahfc_ref_id" => '',
                "applicant_type" => $this->request->get('type_of_applicant'),
                "applicant_subtype" => "primary",
                "first_name" => $this->request->get('first_name'),
                "last_name" => $this->request->get('last_name'),
                "mobile" => $this->request->get('mobile_number'),
                "email" => $this->request->get('email'),
                "pan" => $this->request->get('pan_card'),
                "has_form_60" => "",
                "aadhar_number" => $this->request->get('aadhar_number'),
                "dob" => $this->request->get('dob'),
                "qualification" => $this->dataMapping('QualificationMaster', $this->request->get('education_level')),
                "gender" => strtolower($this->request->get('gender')),
                "marital_status" => $this->request->get('marital_status'),
                "voter_id_no" => "",
                "income_consideration" => true,
                "citizenship" => "",
                "ca_line1" => $this->request->get('current_address_line_1'),
                "ca_line2" => $this->request->get('current_address_landmark'),
                "ca_pincode" => $this->request->get('current_address_pincode'),
                "ca_residence_type" => $this->request->get('current_address_status'),
                "ca_residence_duration" => 1,
                "ca_city" => $this->request->get('current_address_city'),
                "ca_state" => $this->request->get('current_address_state'),
                "pa_line1" => $this->request->get('permanent_address_line_1'),
                "pa_line2" => $this->request->get('permanent_address_landmark'),
                "pa_pincode" => $this->request->get('permanent_address_pincode'),
                "pa_city" => $this->request->get('permanent_address_city'),
                "pa_state" => $this->request->get('permanent_address_state'),
                "pa_residence_type" => $this->request->get('permanent_address_status'),
                "pa_residence_duration" => 1,
                "pp_industry" => "",
                "pp_employment_type" => strtolower($this->request->get('employee_status')),
                "pp_city" => $this->request->get('work_address_city'),
                "pp_pincode" => $this->request->get('work_address_pincode'),
                "pp_org_address_line1" => $this->request->get('work_address_line_1'),
                "pp_org_address_line2" => $this->request->get('work_address_landmark'),
                "pp_state" => $this->request->get('work_address_state'),
                "pp_designation" => $this->request->get('designation'),
                "pp_current_exp_months" => $this->request->get('experience'),
                "pp_salaried_type" => "bank_salaried",
                "pp_gross_salary" => $this->request->get('monthly_income'),
                "pp_total_experience_months" => $this->request->get('experience'),
                "father_name" => $this->request->get('father_name'),
                "mother_maiden_name" => $this->request->get('mother_name'),
                "spouse_name" => "",
                "community" => $this->request->get('applicant_caste'),
                "religion" => $this->request->get('applicant_religion'),
                "alt_mobile" => "",
                "pp_company_name" => $this->request->get('company_name'),
                "pp_business_since" => 5,
                "pp_net_salary" => $this->request->get('monthly_income'),
                "pp_other_income" => 0,
                "pp_credit_card_outstanding" => 0,
                "pp_current_emis" => $this->request->get('current_active_loan_emi'),
                "pp_net_income" => $this->request->get('monthly_income'),
                "pp_other_income_type" => "rent",
                "pp_office_email" => "",
                "pp_office_phone" => "",
                "org_gstn" => "",
                "preferred_language_code" => $this->dataMapping('Language', $this->request->get('preferred_language')),
            ];

            if($this->request->get('applicant_id')) {
                $applicants[0]['applicant_id'] = $this->request->get('applicant_id');
            }
        }
        if ($this->request->get('co_applicant_name')){
            $applicants[] = [
                "ahfc_ref_id" => $this->request->get('co_applicant_id'),
                "applicant_type" => "individual",
                "applicant_subtype" => "co-applicant",
                "first_name" => $this->request->get('co_applicant_name'),
                "last_name" => "",
                "mobile" => $this->request->get('co_applicant_mobile_number'),
                "email" => $this->request->get('co_applicant_email'),
                "pan" => $this->request->get('co_applicant_pan_card'),
                "has_form_60" => "",
                "aadhar_number" => $this->request->get('co_applicant_aadhaar_card'),
                "dob" => $this->request->get('co_dob'),
                "qualification" => 0,
                "gender" => $this->request->get('co_applicant_gender'),
                "marital_status" => "",
                "voter_id_no" => "",
                "income_consideration" => true,
                "citizenship" => "",
                "ca_line1" => "",
                "ca_line2" => "",
                "ca_pincode" => "",
                "ca_residence_type" => "",
                "ca_residence_duration" => "",
                "ca_city" => 0,
                "ca_state" => 0,
                "pa_line1" => "",
                "pa_line2" => "",
                "pa_pincode" => "",
                "pa_city" => 0,
                "pa_state" => 0,
                "pa_residence_type" => "",
                "pa_residence_duration" => "",
                "pp_industry" => "",
                "pp_employment_type" => $this->request->get('co_applicant_employee_status'),
                "pp_city" => 0,
                "pp_pincode" => "",
                "pp_org_address_line1" => "test",
                "pp_org_address_line2" => "",
                "pp_state" => 0,
                "pp_designation" => "",
                "pp_current_exp_months" => $this->request->get('co_applicant_experience'),
                "pp_salaried_type" => "",
                "pp_gross_salary" => 0,
                "pp_total_experience_months" => $this->request->get('co_applicant_experience'),
                "applicant_id" => $this->request->get('co_applicant_id'),
                "father_name" => $this->request->get('co_father_name'),
                "mother_maiden_name" => "",
                "spouse_name" => "",
                "community" => "",
                "religion" => "",
                "alt_mobile" => "",
                "pp_company_name" => $this->request->get('co_applicant_company_name'),
                "pp_business_since" => 5,
                "pp_net_salary" => $this->request->get('monthly_income'),
                "pp_other_income" => 0,
                "pp_credit_card_outstanding" => 0,
                "pp_current_emis" => $this->request->get('co_applicant_current_active_loan_emi'),
                "pp_net_income" => $this->request->get('co_applicant_monthly_income'),
                "pp_other_income_type" => "",
                "pp_office_email" => "",
                "pp_office_phone" => "",
                "org_gstn" => "",
                "preferred_language_code" => $this->dataMapping('Language', $this->request->get('preferred_language')),
            ];

            if($this->request->get('co_applicant_id')) {
                $applicants[1]['applicant_id'] = $this->request->get('co_applicant_id');
            }
        }

        return $applicants;
    }

    private function getBTDetails(){
        return [];
        return [
            "bt_bank_id" => "",
            "bt_outstanding" => "",
            "bt_top_up_amount" => "",
            "bt_top_up_tenure" => ""
        ];
    }

    public function uploadDocument($wrapper = null){
        $fileId = $this->request->get('file_id');
        $param = $this->request->get('param');
        $file = ConsumerApplicationFiles::where('id', $fileId)->first(['id', 'file_path', 'file_type', 'password']);
        $documents = [];

        $documentsCount = HomevilleDocument::where('consumer_application_file_id', $fileId)->first(['id']);

        $homevillLoan = HomevilleLoans::where('application_id', $this->request->get('id'))->first(['case_id', 'response']);
        $homevillLoanResponse = json_decode($homevillLoan->response);

        if (!isset($documentsCount->id)) {
            $s3 = Storage::disk('s3');
            if($s3->exists($file->file_path)) {
                file_put_contents($this->request->get('file_path'), $s3->get($file->file_path));
                $documents = array(
                    "applicant_id"  => $homevillLoanResponse->data->applicants->applicant_id ?? 0,
                    "document_type"   => $this->getDocumentName($this->getFileType(), $file->file_type),
                    "document"     => $this->request->get('file_path'),
                    "documentFor"     => 'applicant', //Values: "applicant", "co-applicant", "guarantor", "application", "disbursement"
                    "is_for"     => null,
                    "application_uuid"     => null, //$fileId,
                    "asset_id"     => null,
                );
            }else{
                $error = new \stdClass();
                $error->description = 'File is missing: '.$file->file_type;
                $this->error = $error;
                return $this;
            }
        }


        return $documents;
    }

    public function uploadDocumentV1($wrapper = null){
        $file_path = $this->request->get('file_path');
        $param = $this->request->get('param');
        $s3 = Storage::disk('s3');
        if ($s3->exists($file_path)){
            $file = $s3->get($file_path);
        }elseif($param == "AADHAR" || $param == "VOTER_ID" || $param == "OTHER"){
            $error = new \stdClass();
            $error->description = 'Aadhar Card or Voter ID or Driving License not masked';
            $this->error = $error;
            return $this;
        }else{
            $error = new \stdClass();
            $error->description = 'File is missing';
            $this->error = $error;
            return $this;
        }
        $fileArray = explode("/", $file_path);
        $file_name = $fileArray[1];
        $file_name_arr = explode(".", $file_name);
        $file_extension = $file_name_arr[1] ?? '';
        if($file_extension == ""){
            $file_name_1 = $fileArray[2];
            $file_name_arr_1 = explode(".", $file_name_1);
            $file_extension = isset($file_name_arr_1[1]) ? $file_name_arr_1[1] : '';
            $file_name = $file_name.$file_extension;
            $file_tmp_path = storage_path().'/'.$file_name;
        }else{
            $file_tmp_path = storage_path().'/'.$file_name;
        }
        file_put_contents($file_tmp_path,$file);
        $mime = "";
        if($file_extension == "jpg" || $file_extension == "jpeg"){
            $mime = "image/jpeg";
        }
        if($file_extension == "png"){
            $mime = "image/png";
        }
        if($file_extension == "pdf"){
            $mime = "application/pdf";
        }

        if($mime == ""){
            $error = new \stdClass();
            $error->description = 'Incorrect File Type';
            $this->error = $error;
            return $this;
        }
        return [
            "applicant_id"  => $this->request->get('homeville_id'),
            "document_type"   => $param,
            "document"     => $file_path,//new \CurlFile($file_tmp_path,$mime,$file_name),
            "documentFor"     => 'applicant', //Values: "applicant", "co-applicant", "guarantor", "application", "disbursement"
            "is_for"     => null,
            "application_uuid"     => null,
            "asset_id"     => null,
        ];
    }

    public function createLoan($wrapper = null)
    {
        return [];
    }

    private function initApplicationData(){

        $this->solar = !_env('APP_CONNECTION') ? 6 : 24;

        $application = ConsumerApplication::where('id', $this->request->get('id'))
->with('emi', 'proFormaInvoice', 'merchant', 'application_element', 'bank_details', 'foir', 'offer')->first(
    ['id', 'offer_id', 'purpose', 'approved_amount', 'applicant_id', 'co_applicant_id', 'aadhaar_card', 'co_applicant_aadhaar_card', 'dob', 'co_applicant_dob',
        'co_applicant_gender', 'co_applicant_pan_card', 'co_applicant_mobile_number', 'co_applicant_name',
        'name', 'email', 'pan_card', 'mobile_number', 'gender', 'current_address_line_1', 'current_address_pincode', 'current_address_status', 'current_address_city',
        'current_address_state', 'current_address_landmark', 'marital_status', 'permanent_address_line_1', 'permanent_address_pincode', 'permanent_address_status', 'permanent_address_city',
        'permanent_address_state', 'permanent_address_landmark', 'merchant_id','monthly_income','co_applicant_monthly_income', 'co_applicant_company_name', 'company_name',
        'employee_status', 'co_applicant_employee_status','work_address_line_1', 'work_address_state', 'work_address_city', 'work_address_pincode', 'work_address_landmark',
        'experience', 'co_applicant_experience'

    ]);

//        if (!isset($application->bank_details->id)){
//            $error = new \stdClass();
//            $error->description = 'Customer bank details required';
//            $this->error = $error;
//            return $this;
//        }

        $loan_subcategory = 'home_decor';
        if ($this->solar && $application->application_element->type_of_customer){
            $loan_subcategory = 'solar_rooftop_commercial';
            if ($application->application_element->type_of_customer == 1){
                $loan_subcategory = 'solar_rooftop_residential';
            }
        }

        $loan_purpose = 'interior_financing';
        if ($this->solar && $application->application_element->type_of_customer){
            if ($application->application_element->type_of_customer == 1 || $application->application_element->type_of_customer == 4){
                $loan_purpose = 'residence';
            }else if ($application->application_element->type_of_customer == 2){
                $loan_purpose = 'atta_chakki';
            }else if ($application->application_element->type_of_customer == 3){
                $loan_purpose = 'c_and_i';
            }else if ($application->application_element->type_of_customer == 5){
                $loan_purpose = 'school';
            }
        }

        $type_of_applicant = 'individual';
        /*if ($loan_purpose == 'c_and_i'){
            $type_of_applicant = 'non-individual';
        }else{
            $type_of_applicant = 'individual';
        }*/


        $net_tenure = $application->emi->tenure;

        $merchant_collected_advance_amount = $application->proFormaInvoice && $application->proFormaInvoice->merchant_collected_advance_amount ? $application->proFormaInvoice->merchant_collected_advance_amount : 0;

        if (!$merchant_collected_advance_amount){
            if ($application->offer->advance_type == 'emi'){
                $net_tenure = $application->emi->tenure - $application->emi->advance_emi;
            }
        }

        $names = explode(' ',$application->name);
        $first_name = $names[0];
        $last_name = end($names);


        if ($application->current_address_pincode){
            $instance = $this->getInstance(['pincode' => $application->current_address_pincode]);

            $wrapperRes = $instance['wrapperMethods']->getCityByPincode($instance['wrapper']);

            if (isset($wrapperRes->response->status) && $wrapperRes->response->status == 'success'){
                $currentStateId = $wrapperRes->response->data->state_id;
                $currentCityId = $wrapperRes->response->data->city_id;
            }
        }

        if ($application->permanent_address_pincode){
            $instance = $this->getInstance(['pincode' => $application->permanent_address_pincode]);

            $wrapperRes = $instance['wrapperMethods']->getCityByPincode($instance['wrapper']);

            if (isset($wrapperRes->response->status) && $wrapperRes->response->status == 'success'){
                $permanentStateId = $wrapperRes->response->data->state_id;
                $permanentCityId = $wrapperRes->response->data->city_id;
            }
        }

        /*if (isset($application->bank_details->id)){
            $bank_master = DB::table('hv_bank_master')->where('bank_name', $application->bank_details->bank_name)->first(['bank_id']);
            if (isset($bank_master->bank_id)){
                $bank_id = $bank_master->bank_id;
            }
        }

        if (!isset($bank_id)){
            $error = new \stdClass();
            $error->description = 'Bank Not Found/Correctly Mapped in The Homeville Bank Master';
            $this->error = $error;
            return $this;
        }*/

        if (!isset($currentStateId) && !isset($currentCityId)){
            $error = new \stdClass();
            $error->description = 'Current City & State Mapping not found with homeville';
            $this->error = $error;
            return $this;
        }

        if (!isset($permanentStateId) && !isset($permanentCityId)){
            $error = new \stdClass();
            $error->description = 'Permanent City & State Mapping not found with homeville';
            $this->error = $error;
            return $this;
        }

        $current_address_status = $application->current_address_status == 'OWNED' ? 'self owned' : ($application->current_address_status == 'RENTED' ? 'rented' : ($application->current_address_status == 'Self Owned') ? 'self owned' : ($application->current_address_status == 'PARENTS HOUSE') ? 'with parents' : ($application->current_address_status == 'Company Allotted' ? 'company provided' : ($application->current_address_status == 'Rented With Friend' ? 'paying guest' : '')));

        if (empty($current_address_status)){
            $error = new \stdClass();
            $error->description = 'Current Address Residence Type is Mandatory';
            $this->error = $error;
            return $this;
        }

        $permanent_address_status = $application->permanent_address_status == 'OWNED' ? 'self owned' : ($application->permanent_address_status == 'RENTED' ? 'rented' : ($application->permanent_address_status == 'Self Owned') ? 'self owned' : ($application->permanent_address_status == 'PARENTS HOUSE') ? 'with parents' : ($application->permanent_address_status == 'Company Allotted' ? 'company provided' : ($application->permanent_address_status == 'Rented With Friend' ? 'paying guest' : '')));

        if (empty($permanent_address_status)){
            $error = new \stdClass();
            $error->description = 'Permanent Address Residence Type is Mandatory';
            $this->error = $error;
            return $this;
        }

        if (!$application->application_element->inverter_gross_project_amount){
            $error = new \stdClass();
            $error->description = 'Inverter Gross Project Amount is Mandatory';
            $this->error = $error;
            return $this;
        }

        $applicant_id = 0;
        $co_applicant_id = 0;
        if($this->is_update){
            $applicant_id = $this->request->get('applicant_id') ?? 0;
            $co_applicant_id = $this->request->get('co_applicant_id') ?? 0;
        }

        $net_loan_amount = $application->approved_amount;
        if (!$merchant_collected_advance_amount) {
            $net_loan_amount -= $application->emi->upfront_from_customer;
        }

        $company_name = $application->company_name ?? '';
        $co_applicant_company_name = $application->co_applicant_company_name ?? '';

        if ($company_name && !filter_var($company_name, FILTER_VALIDATE_INT) === false) {
            $_company_name = Company::where('id', $company_name)->first(['company']);
            if (isset($_company_name->company)) {
                $company_name = $_company_name->company;
            }
        }

        if ($co_applicant_company_name && !filter_var($co_applicant_company_name, FILTER_VALIDATE_INT) === false) {
            $_company_name = Company::where('id', $co_applicant_company_name)->first(['company']);
            if (isset($_company_name->company)) {
                $co_applicant_company_name = $_company_name->company;
            }
        }

        if ($application->work_address_pincode){
            $instance = $this->getInstance(['pincode' => $application->work_address_pincode]);

            $wrapperRes = $instance['wrapperMethods']->getCityByPincode($instance['wrapper']);

            if (isset($wrapperRes->response->status) && $wrapperRes->response->status == 'success'){
                $workStateId = $wrapperRes->response->data->state_id;
                $workCityId = $wrapperRes->response->data->city_id;
            }
        }

        if (!isset($workStateId) && !isset($workCityId)){
            $error = new \stdClass();
            $error->description = 'Work City & State Mapping not found with homeville';
            $this->error = $error;
            return $this;
        }

        $current_active_loan_emi = $this->getCurrentActiveLoanEMI($application);

        if($application->employee_status){
            if($application->employee_status == 'SALARIED'){
                $employee_status = 'salaried';
            }else if($application->employee_status == 'Self Employed - Professional'){
                $employee_status = 'sep';
            }else if($application->employee_status == 'HOUSEWIFE'){
                $employee_status = 'house-wife';
            }else if($application->employee_status == 'UNEMPLOYED'){
                $employee_status = 'not-considered-as-income';
            }else if($application->employee_status == 'Self Employed - Business'){
                $employee_status = 'self-employed';
            }
        }

        if($application->co_applicant_employee_status){
            if($application->co_applicant_employee_status == 'SALARIED'){
                $co_applicant_employee_status = 'salaried';
            }else if($application->co_applicant_employee_status == 'Self Employed - Professional'){
                $co_applicant_employee_status = 'sep';
            }else if($application->co_applicant_employee_status == 'HOUSEWIFE'){
                $co_applicant_employee_status = 'house-wife';
            }else if($application->co_applicant_employee_status == 'UNEMPLOYED'){
                $co_applicant_employee_status = 'not-considered-as-income';
            }else if($application->co_applicant_employee_status == 'Self Employed - Business'){
                $co_applicant_employee_status = 'self-employed';
            }
        }

        if (!isset($employee_status)){
            $error = new \stdClass();
            $error->description = 'Applicant Employee Type is mandatory';
            $this->error = $error;
            return $this;
        }

        if ($application->co_applicant_name && !isset($co_applicant_employee_status)){
            $error = new \stdClass();
            $error->description = 'Co-Applicant Employee Type is mandatory';
            $this->error = $error;
            return $this;
        }

        if(!$application->application_element->education_level){
            $error = new \stdClass();
            $error->description = 'Education Level is mandatory';
            $this->error = $error;
            return $this;
        }


        $this->request->merge([
            'loan_application_no' => $application->proFormaInvoice->loan_application_no,
            'category_type' => $application->purpose == $this->solar ? 'solar_loan' : ($application->purpose == $this->home_decore ? 'home_decor' : 'business_loan'),
            'loan_subcategory' => $loan_subcategory,
            'loan_purpose' => $loan_purpose,
            'loan_amount' => $net_loan_amount,
            'market_value' => $application->purpose == $this->solar ? $application->application_element->inverter_gross_project_amount : $application->loan_amount,
            'loan_tenure' => $net_tenure,
            'applicant_id' => $applicant_id,
            'co_applicant_id' => $co_applicant_id,
            'first_name' => $first_name,
            'last_name' => $last_name,
            'father_name' => $application->application_element->father_name,
            'co_father_name' => $application->application_element->co_applicant_father_name,
            'mother_name' => $application->application_element->mother_name,
            'aadhar_number' => $application->aadhaar_card,
            'co_applicant_aadhaar_card' => $application->co_applicant_aadhaar_card,
            'dob' => $application->dob,
            'co_dob' => $application->co_applicant_dob,
            'co_applicant_gender' => $application->co_applicant_gender,
            'co_applicant_pan_card' => $application->co_applicant_pan_card,
            'co_applicant_email' => $application->co_applicant_email,
            'co_applicant_mobile_number' => $application->co_applicant_mobile_number,
            'name' => $application->name,
            'email' => $application->email,
            'pan_card' => $application->pan_card,
            'mobile_number' => $application->mobile_number,
            'gender' => $application->gender,
            'bank_details' => $application->bank_details,
            'bank_id' => $bank_id ?? 0,
            'current_address_line_1' => $application->current_address_line_1,
            'current_address_pincode' => $application->current_address_pincode,
            'current_address_status' => $current_address_status,
            'current_address_city' => $currentCityId,
            'current_address_state' => $currentStateId,
            'current_address_landmark' => $application->current_address_landmark,
            'permanent_address_line_1' => $application->permanent_address_line_1,
            'permanent_address_pincode' => $application->permanent_address_pincode,
            'permanent_address_status' => $permanent_address_status,
            'permanent_address_city' => $permanentCityId,
            'permanent_address_state' => $permanentStateId,
            'permanent_address_landmark' => $application->permanent_address_landmark,
            'marital_status' => strtolower($application->marital_status),
            'reference_name_1' => $application->application_element->reference_name_1,
            'reference_contact_1' => $application->application_element->reference_contact_1,
            'applicant_religion' => $this->dataMapping('Religion', $application->application_element->applicant_religion),
            'applicant_caste' => $this->dataMapping('Community', $application->application_element->applicant_caste),
            'education_level' => $application->application_element->education_level,
            'monthly_income' => $application->monthly_income,
            'co_applicant_monthly_income' => $application->co_applicant_monthly_income,
            'company_name' => $company_name,
            'co_applicant_company_name' => $co_applicant_company_name,
            'employee_status' => $employee_status,
            'co_applicant_employee_status' => $co_applicant_employee_status ?? '',
            'work_address_line_1' => $application->work_address_line_1,
            'work_address_landmark' => $application->work_address_landmark,
            'work_address_city' => $workCityId,
            'work_address_state' => $workStateId,
            'work_address_pincode' => $application->work_address_pincode,
            'current_active_loan_emi' => $current_active_loan_emi['applicant'],
            'co_applicant_current_active_loan_emi' => $current_active_loan_emi['co_applicant'],
            'experience' => $application->experience ?? 0,
            'co_applicant_experience' => $application->co_applicant_experience ?? 0,
            'designation' => $application->application_element->designation ?? 0,
            'preferred_language' => strtolower($application->application_element->preferred_language) ?? 'english',
            'type_of_applicant' => $type_of_applicant,
        ]);
    }

    public function addAsset($wrapper = null)
    {

        $application = ConsumerApplication::where('id', $this->request->get('id'))
            ->with('application_element', 'bank_details', 'merchant')->first(['id', 'merchant_id']);

        $homevillLoan = HomevilleLoans::where('application_id', $this->request->get('id'))->first(['case_id']);

        $currentCityId = 0;
        $currentStateId = 0 ;

        if (isset($application->application_element->installation_address_pincode)){
            $instance = $this->getInstance(['pincode' => $application->application_element->installation_address_pincode]);

            $wrapperRes = $instance['wrapperMethods']->getCityByPincode($instance['wrapper']);

            if (isset($wrapperRes->response->status) && $wrapperRes->response->status == 'success'){
                $currentStateId = $wrapperRes->response->data->state_id;
                $currentCityId = $wrapperRes->response->data->city_id;
            }
        }

        if (!isset($currentStateId) && !isset($currentCityId)){
            $error = new \stdClass();
            $error->description = 'Current City & State Mapping for installation address not found with homeville';
            $this->error = $error;
            return $this;
        }

        if (!$application->application_element->inverter_KW_installation){
            $error = new \stdClass();
            $error->description = 'Inverter KW Installation is Mandatory';
            $this->error = $error;
            return $this;
        }

        return [
            "case_id" => $homevillLoan->case_id ?? '',
            "asset_details" => [
                [
                    "asset_ahfc_ref" => $application->id,
                    "developer_name" => "Testing",
                    "property_type" => "new",
                    "asset_status" => "ready_to_move_in",
                    "type_of_asset" => "structure_with_land",
                    "address_line1" => $application->application_element->installation_address_line_1,
                    "pincode" => $application->application_element->installation_address_pincode,
                    "market_value" => $application->loan_amount,
                    "build_up_area" => 100,
                    "security_type" => "registered",
                    "plan_approval_authority" => "municipal_corporation",
                    //"agreement_value" => 0,
                    "survey_no" => 0,
                    "plot_no" => 0,
                    "floor_no" => 0,
                    "unit_no" => 0,
                    "city" => $currentCityId,
                    "state" => $currentStateId,
                    "project_name" => null,
                    "asset_subcategory" => "commercial",
                    "asset_description" => "commercial_plot",
                    "society_name" => "",
                    "locality_name" => "",
                    "nature_of_land" => "leasehold",
                    "carpet_area" => 0,
                    "asset_id" => 0,
                    "subsidy_amount" => 0,
                    "discom_provider" => strtoupper($application->application_element->discom_service_provider),
                    'discom_provider_other' => strtolower($application->application_element->discom_service_provider) == 'other' ? $application->application_element->other_discom_service_provider : '',
                    "downpayment" => $application->emi->upfront_from_customer,
                    "flat_rate" => $application->emi->interest_rate,
                    "kw_installation" => $application->application_element->inverter_KW_installation,
                    "latitude" => "string",
                    "longitude" => "string",
                    "merchant_name" => _env('APP_CONNECTION') ? $application->merchant->merchant_name : 'MYSUN',
                    "merchant_name_other" => "",
                    "modal_description" => $application->application_element->inverter_model_description,
                    "monthly_power_bill" => $application->application_element->inverter_monthly_power_bill,
                    "power_saving_estimated" => $application->application_element->inverter_power_savings,
                    "power_saving_income" => 0,
                    "premises" => "parents_house",
                    "quotation_identified" => 0,
                    "solar_inverter" => $this->dataMapping('SolarPanel', null) == $application->application_element->inverter ? strtoupper($application->application_element->inverter) : 'OTHER',
                    "solar_inverter_other" => strtoupper($application->application_element->inverter),
                    "solar_panel" => $this->dataMapping('SolarPanel', null) == $application->application_element->panel ? strtoupper($application->application_element->panel) : 'OTHER',
                    "solar_panel_other" => strtoupper($application->application_element->panel)
                ]
            ]
        ];

        /*return [
            "case_id" => $homevillLoan->case_id ?? '',
            "asset_details" => [
                [
                    "asset_ahfc_ref" => "",
                    "developer_name" => "",
                    "property_type" => "new",
                    "asset_status" => "ready_to_move_in",
                    "type_of_asset" => "structure_with_land",
                    "address_line1" => $application->application_element->installation_address_line_1,
                    "pincode" => $application->application_element->installation_address_pincode,
                    "market_value" => "",
                    "build_up_area" => "",
                    "security_type" => "",
                    "plan_approval_authority" => "",
                    "agreement_value" => 0,
                    "survey_no" => 0,
                    "plot_no" => 0,
                    "floor_no" => 0,
                    "unit_no" => 0,
                    "project_name" => null,
                    "asset_subcategory" => "",
                    "asset_description" => "",
                    "society_name" => "",
                    "locality_name" => "",
                    "nature_of_land" => "",
                    "carpet_area" => "",
                    "asset_id" => 0,
                    "asset_legal_validations" => [
                        [
                            "legal_owners" => [
                                [
                                    "id" => 0
                                ]
                            ],
                            "type_of_finance" => "sole",
                            "legal_asset_boundary" => [
                                "east" => "",
                                "west" => "",
                                "south" => "",
                                "north" => ""
                            ],
                            "spcl_terms_suggested" => "",
                            "asset_legal_validation_id" => 0
                        ]
                    ],
                    "asset_technical_validations" => [
                        [
                            "technical_asset_boundary" => [
                                "east" => "",
                                "west" => "",
                                "south" => "",
                                "north" => ""
                            ],
                            "built_up_area" => 0,
                            "area_considered" => 0,
                            "area_as_per_actual" => 0,
                            "fair_market_value" => 0,
                            "distress_value" => 0,
                            "realizable_value" => 0,
                            "asset_technical-validation_id" => 0
                        ]
                    ]
                ]
            ]
        ];*/
    }

    public function getToken($wrapper = null)
    {
        return [
            "client_id" => _env('HOMEVILLE_CLIENT_ID'),
            "client_secret" => _env('HOMEVILLE_CLIENT_SECRET')
        ];
    }

    public function getStateMaster($wrapper = null)
    {
        // TODO: Implement getStateMaster() method.
    }

    public function getCityMaster($wrapper = null)
    {
        // TODO: Implement getCityMaster() method.
    }

    public function getCityByPincode($wrapper = null)
    {

    }

    private function getCurrentActiveLoanEMI($application){
        $data = [];
        $gradeController = new GradeController($this->request);
        foreach ($application->foir as $foir) {

            if ($foir->AccountType != 'Credit Fair EMI') {
                if ($foir->applicant_type == 1) {
                    $gradeController->setFOIRAttributes($foir);
                }
            }
        }

        $data['applicant'] = $gradeController->total_existing_emi ?? 0;

        $gradeController = new GradeController($this->request);
        foreach ($application->foir as $foir) {

            if ($foir->AccountType != 'Credit Fair EMI') {
                if ($foir->applicant_type == 2) {
                    $gradeController->setFOIRAttributes($foir);
                }
            }
        }

        $data['co_applicant'] = $gradeController->total_existing_emi ?? 0;

        return $data;
    }

    public function getInstance($args = array()){
        $wrapper = new Wrapper();
        $wrapperMethods = $wrapper->register(HomevilleMethods::class);
        $wrapper->payload->addPayload(new Request($args));
        return [
            'wrapperMethods' => $wrapperMethods,
            'wrapper' => $wrapper
        ];
    }

    public function getBankMaster($wrapper = null)
    {
        return [];
    }

    public function loanTerms($wrapper = null)
    {
        $application = ConsumerApplication::where('id', $this->request->get('id'))
            ->with('emi', 'proFormaInvoice', 'merchant', 'offer')->first(['id', 'offer_id', 'merchant_id', 'approved_amount']);

        $homevillLoan = HomevilleLoans::where('application_id', $application->id)->first(['case_id']);


        $net_tenure = $application->emi->tenure;

        $net_loan_amount = $application->approved_amount;

        $merchant_collected_advance_amount = $application->proFormaInvoice && $application->proFormaInvoice->merchant_collected_advance_amount ? $application->proFormaInvoice->merchant_collected_advance_amount : 0;

        if (!$merchant_collected_advance_amount){
            $net_loan_amount -= $application->emi->upfront_from_customer;
            if ($application->offer->advance_type == 'emi'){
                $net_tenure = $application->emi->tenure - $application->emi->advance_emi;
            }
        }

        $subvention = (new ConsumerApplicationController())->getSubventionDetails($application, false);

        $disbursementController = new DisbursementController($this->request);
        $insurance_amount = $disbursementController->isCustomerPayingInsuranceFee($application);

        return [
            "case_id" => $homevillLoan->case_id ?? '',
            "loan_percentage" => 20,
            "cust_roi" =>  $application->emi->annualised_interest,
            "tenure" => $net_tenure,
            "moratorium" => 0,
            "emi_day" => 5,
            "dsra_count" => 0,
            "set_to" => 1,
            "roi_type" => "fixed",
            "notes" => "",
            "pre_emi_period" => 1,
            "charges" => [
                "processing_fee" => $application->emi->processing_fee,
                "property_insurance_amount" => $insurance_amount,
                'merchant_subvention_fee' => $subvention['WithGST'],
                //"pre_emi_period" => 1
            ]
        ];
    }

    public function getFileType($isIncome = false){
        if ($isIncome){
            return [
                //'salary_slip' => 'salary_slip',
                'bank_statement_doc' => 'bank_statement',
            ];
        }
        return [
            'aadhar' => ['aadhar_card_masked', 'aadhar_card','aadhar_card_back'],
            //'aadhar' => ['aadhar_card_back_masked', 'aadhar_card_back'],
            'pancard' => 'pan_card',
            'bank_statement_doc' => ['bank_statement', 'bank_statement_2', 'bank_statement_3', 'bank_statement_5', 'bank_statement_6'],
            'photograph' => 'customer_photo',
            'other' => $this->getAvailableDocumentLists()
        ];
    }

    private function getAvailableDocumentLists(){
        return [
            'aadhar_xml',
            'consent_logs',
            'advance_amount_receipt',
            'atta_chakki_video',
            'agreement',
            'equifax_report',
            'call_recording',
            'cpv',
            'credit_appraisal_memo',
            'gas_bill',
            'electricity_bill',
            'finbit_analysis',
            'foir',
            'gst_certificate',
            'hypothecation_agreement',
            'insurance_payment_receipt',
            'itr',
            'mca',
            'nach',
            'panvalidation',
            'passbook_copy',
            'passport_front',
            'passport_back',
            'processing_fee_receipt',
            'prode42',
            'rent_agreement',
            'salary_slip',
            'security_cheques',
            'sale_deed',
            'self_attested',
            'self_attested_aadhar',
            'self_attested_pan',
            'sanction_letter',
            'shop_act',
            'solar_installation_proof',
            'tfr',
            'reference_1',
            'reference_2',
            'udyog_aadhaar_certificate',
            'utilitybillvalidation',
            'driving_license',
            'votar_id_front',
            'votar_id_back',
            'virtual_account',
            'house_verification_photo',
            'business_verification_photo',
            'valuer_report',
            'technical_feasibility_report',
            'panel_installation_photo',
            'solar_quotation',
            'gst_return_year_one',
            'gst_return_year_two',
            'gst_return_year_three',
            'current_address_proof',
            'other',
            'co_applicant_aadhar_card',
            'co_applicant_aadhar_card_back',
            'co_applicant_bank_statement',
            'co_applicant_equifax_report',
            'co_applicant_customer_photo',
            'co_applicant_pan_card',
            'co_applicant_gst',
            'co_applicant_itr',
            'co_applicant_self_attested',
            'original_seen_verified',
            'proforma',
            'pro_forma_invoice'];
    }

    public function getDocumentName($fileTypes, $get_key = false){
        $data = [];
        $search_key = false;
        foreach ($fileTypes as $key => $fileType){
            if (is_array($fileType)){
                foreach ($fileType as $item) {
                    if ($get_key == $item){
                        $search_key = $key;
                        break;
                    }
                    $data[] = $item;
                }
            }else{
                $data[] = $fileType;
                if ($get_key == $fileType){
                    $search_key = $key;
                    break;
                }
            }
        }

        return $search_key ? $search_key : $data;
    }

    public function getQualificationMaster($wrapper = null)
    {
        return [];
    }

    public function dataMapping($key, $value){
        $data = [
            'QualificationMaster' => [
                '10th Grade' => 17,
                '12th Grade' => 157,
                'Graduation' => 151,
                'Post graduation' => 448,
                'Masters' => 19
            ],
            'Community' => [
                'Schedule Tribe' => 'st',
                'General' => 'general',
                'Minority' => 'minority',
                'Schedule Caste' => 'sc',
                'Other Backward Class' => 'obc',
                'Others' => 'other'
            ],
            'Religion' => [
                'HINDU' => 'hindu',
                'MUSLIM' => 'muslim',
                'CHRISTIAN' => 'christian',
                'SIKHS' => 'sikh',
                'SIKH' => 'sikh',
                'JAINS' => 'other',
                'JAIN' => 'other',
                'ZOROASTRIANS' => 'other',
                'BUDDHIST' => 'buddhist',
                'PARSI' => 'other',
                'BHAHAI' => 'other',
                'Others' => 'other'
            ],
            'Language' => [
                "bengali" => "ben",
                "english" => "eng",
                "gujarati" => "guj",
                "hindi" => "hin",
                "kannada" => "kan",
                "marathi" => "mar",
                "punjabi" => "pan",
                "tamil" => "tam",
                "telugu" => "tel",
                "urdu" => "urd"
            ],
            'SolarPanel' => [
                "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",
                "vikram solar",
                "goldi solar pvt. ltd",
                "saatvik green energy",
                "servotech power systems ltd",
                "emmvee photovoltaic power private limited",
                "saatvik green energy",
                "microtek",
                "bluebird solar",
                "swelect energy systems",
                "insolation energy",
                "renewable energy corporation",
                "bamani solar solutions |utl solar shoppe",
                "aadhi solar",
                "other"
            ]

        ];

        return $value ? $data[$key][$value] : $data[$key];
    }

    public function generateDocument($wrapper = null)
    {
        $consumerApplicationElement = ConsumerApplicationElement::where('application_id', $this->request->get('id'))->first(['preferred_language']);
        $application = ConsumerApplication::with(['merchant' => function($query){
            return $query->select(['id','address']);
        }])->where('id', $this->request->get('id'))->first(['id','merchant_id']);

        return [
            "doc_type" => $this->request->get('doc_type'),
            "loanAgreementDate" => Carbon::now()->toDateString(),
            "solarEmiStartDate" => $this->request->get('first_emi_date'),
            "language" => $this->dataMapping('Language', strtolower($consumerApplicationElement->preferred_language) ?? 'english'),
            "merchantAddress" => $application->merchant->address,
            'dateOfExecution' => Carbon::now()->toDateString(),
            'transactionDocument' => '1.Loan cum Hypothecation Agreement 2.Supplementary Solar Agreement 3.Key Fact Statement.'
        ];
    }

    public function signRequestMergeDocument($wrapper = null)
    {

        $application = ConsumerApplication::where('id', $this->request->get('id'))->first(['name', 'mobile_number', 'approved_amount', 'co_applicant_name', 'co_applicant_mobile_number']);

        $required_sign = [];
        foreach($this->request->get('signatories') as $invitee){
            if($invitee->name) {
                $required_sign[] = [
                    "name" => $invitee->name,
                    "identifier" => $invitee->email
                ];
            }
        }

        $required_sign[] = [
            'name' => ucwords(strtolower(str_replace('  ', ' ', $application->name))),
            'identifier' => $application->mobile_number,
        ];

        if ($application->co_applicant_name && $application->co_applicant_mobile_number){
            $required_sign[] = [
                'name' => ucwords(strtolower(str_replace('  ', ' ', $application->co_applicant_name))),
                'identifier' => $application->co_applicant_mobile_number,
            ];
        }


        if(isset($application->approved_amount) && $application->approved_amount <= 500000){
            $required_sign[] = [
                "name" => _env('LEEGALITY_CF_PARTY_NAME'),
                "identifier" => _env('LEEGALITY_CF_PARTY_EMAIL')
            ];
        }else{
            $required_sign[] = [
                "name" => _env('LEEGALITY_FIRST_PARTY_NAME'),
                "identifier" => _env('LEEGALITY_FIRST_PARTY_EMAIL')
            ];
        }



        $document_lists = [];
        foreach($this->request->get('document_lists') as $doc){
            $document_lists[] = [
                "id" => $doc['id'],
                'application_id' => (int)$this->request->get('platform_reference_id'),
                "file_category" => $doc['file_category']
            ];
        }

        $tag = 'DL-300-undefined';
        if(isset($application->approved_amount) && $application->approved_amount <= 500000){
            $tag = 'MH-500-Homeville';
        }

        return [
                "case_id" => $this->request->get('case_id'),
                "documents" => [
                    "applicants" => [],
                    "assets" => [],
                    "applications" => array_reverse($document_lists, true)
                ],
                "required_sign" => $required_sign,
                "estamp" => [
                    "tag" => $tag,
                    "count" => 1
                    ]
                ];
    }

    public function generateNACHMandate($wrapper = null)
    {
        return [
            'nach_type' => 'link',
            'bank_id' => $this->request->get('bank_id'),
            'provider' => 'lotuspay',
            'email_id' => $this->request->get('email_id'),
            'mobile_no' => $this->request->get('mobile_no')
        ];
    }

    public function getApplicantBankDetails($wrapper = null){
        return [];
    }

    public function masterDocumentAPI($wrapper = null)
    {
        return [];
    }

    public function getFormFields($wrapper = null)
    {
        return [];
    }

    public function getListOfESign($wrapper = null)
    {
        return [];
    }

    public function getDocumentId($wrapper = null)
    {
        return [];
    }

    public function getSolarDetails($wrapper = null)
    {
        return [];
    }
}
