<?php

namespace App\Method\Homeville\Response;

use App\HomevilleAssets;
use App\HomevilleDocument;
use App\HomevilleDocumentInfo;
use App\HomevilleLoans;
use App\HomevilleMandate;
use App\HomevilleTerms;
use App\Method\Homeville\Helpers\HomevilleHelper;
use App\QualificationMaster;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Input;

class Response implements HomevilleHelper
{
    public $errorBag;
    public $response;
    /**
     * @var mixed
     */
    private $request;


    public function resolveResponse($func, $res, $request = null){

        if ($request)
            $this->request = $request;

        if(method_exists($this, $func)){
            return $this->$func($res);
        }
        return array();
    }

    public function createApplication($wrapper)
    {
        if ($this->isError($wrapper)){
            return $this;
        }

        if (isset($wrapper->status) && $wrapper->status == 'success' && isset($wrapper->data)){
            if ($wrapper->data->case_id){
                $homevilleLoan = HomevilleLoans::where('application_id', Input::get('id'))->first(['id']);
                if (!isset($homevilleLoan->id)){
                    $homevilleLoan = new HomevilleLoans();
                    $case_id = $wrapper->data->case_id;
                    $homevilleLoan->fill([
                        'application_id' => Input::get('id'),
                        'case_id' => $case_id,
                        'response' => json_encode($wrapper),
                        'status' => 'success'
                    ]);
                    $homevilleLoan->save();
                }
            }
        }

        $this->response = $wrapper;
        return $this;
    }

    public function uploadDocument($wrapper)
    {
        if ($this->isError($wrapper)){
            return $this;
        }

        if (isset($wrapper->status) && $wrapper->status == 'success' && isset($wrapper->data)){
            $homevilleDocument = HomevilleDocument::where('application_id', Input::get('id'))->where('consumer_application_file_id', $wrapper->data->document_id)->first(['id']);
            if (!isset($homevilleDocument->id)){
                $homevilleDocument = new HomevilleDocument();
                $homevilleDocument->fill([
                    'application_id' => Input::get('id'),
                    'consumer_application_file_id' => $this->request->request->get('consumer_application_file_id'),
                    'response' => json_encode($wrapper),
                    'user_id' => Auth::check() ? Auth::user()->id : 107
                ]);
                $homevilleDocument->save();
            }
        }

        $this->response = $wrapper;
        return $this;
    }

    public function createLoan($wrapper)
    {
        if ($this->isError($wrapper)){
            return $this;
        }

        $this->response = $wrapper;
        return $this;
    }

    public function addAsset($wrapper)
    {
        if ($this->isError($wrapper)){
            return $this;
        }

        if (isset($wrapper->status) && $wrapper->status == 'success' && isset($wrapper->data)){
            if ($wrapper->data->asset_id){
                $homevilleAssets = HomevilleAssets::where('application_id', Input::get('id'))->first(['id']);
                if (!isset($homevilleAssets->id)){
                    $homevilleAssets = new HomevilleAssets();
                    $homevilleAssets->fill([
                        'application_id' => Input::get('id'),
                        'response' => json_encode($wrapper),
                        'status' => 'success'
                    ]);
                    $homevilleAssets->save();
                }
            }
        }

        $this->response = $wrapper;
        return $this;
    }

    public function getToken($wrapper)
    {
        if ($this->isError($wrapper)){
            return $this;
        }

        $this->response = $wrapper;
        return $this;
    }

    public function getStateMaster($wrapper)
    {
        if ($this->isError($wrapper)){
            return $this;
        }

        $this->response = $wrapper;
        return $this;
    }

    public function getCityMaster($wrapper)
    {
        if ($this->isError($wrapper)){
            return $this;
        }

        $this->response = $wrapper;
        return $this;
    }

    public function getCityByPincode($wrapper)
    {
        if ($this->isError($wrapper)){
            return $this;
        }

        $this->response = $wrapper;
        return $this;
    }

    public function getBankMaster($wrapper)
    {

    }

    public function loanTerms($wrapper)
    {
        if ($this->isError($wrapper)){
            return $this;
        }

        if (isset($wrapper->status) && $wrapper->status == 'success' && isset($wrapper->data)){
            $homevilleAssets = HomevilleTerms::where('application_id', Input::get('id'))->first(['id']);
            if (!isset($homevilleAssets->id)){
                $homevilleAssets = new HomevilleTerms();
                $homevilleAssets->fill([
                    'application_id' => Input::get('id'),
                    'response' => json_encode($wrapper),
                    'status' => 'success'
                ]);
                $homevilleAssets->save();
            }
        }

        $this->response = $wrapper;
        return $this;
    }

    private function isError($wrapper){
        if ((isset($wrapper->status) && $wrapper->status == 'error') || isset($wrapper->error)) {
            $this->errorBag['Error'] = $wrapper->errors ?? ($wrapper->error->description ?? $wrapper->message);
            return true;
        }
        if (isset($wrapper->message) && $wrapper->message == 'Unauthenticated'){
            $wrapper->message = $this->errorBag['Error'];
            return true;
        }
        return false;
    }

    public function updateApplication($wrapper)
    {
        if ($this->isError($wrapper)){
            return $this;
        }

        $this->response = $wrapper;
        return $this;
    }

    public function getQualificationMaster($wrapper)
    {
        if ($this->isError($wrapper)){
            return $this;
        }

        if (isset($wrapper->status) && $wrapper->status == 'success' && isset($wrapper->data)) {
            $data = [];
            $date = Carbon::now()->toDateTimeString();
            foreach($wrapper->data as $item){
                $data[] = [
                    'qualification_id' => $item->id,
                    'name' => $item->name,
                    'created_at' => $date
                ];
            }
            QualificationMaster::insert($data);
        }

        $this->response = $wrapper;
        return $this;
    }

    public function generateDocument($wrapper)
    {
        if ($this->isError($wrapper)){
            return $this;
        }

        $data = $wrapper->data[0] ?? $wrapper;
        $homevilleDocumentInfo = new HomevilleDocumentInfo();
        $homevilleDocumentInfo->application_id = $this->request->get('id');
        $homevilleDocumentInfo->case_id = $this->request->get('case_id');
        $homevilleDocumentInfo->link = $data->documentUrl;
        $homevilleDocumentInfo->doc_type = $this->request->get('doc_type');
        $homevilleDocumentInfo->save();

        $this->response = $wrapper;
        return $this;
    }

    public function signRequestMergeDocument($wrapper)
    {
        if ($this->isError($wrapper)){
            return $this;
        }

        // if (isset($wrapper->data->documentId)) {
            $homevilleDocumentInfo = new HomevilleDocumentInfo();
            $homevilleDocumentInfo->application_id = $this->request->get('id');
            $homevilleDocumentInfo->case_id = $this->request->get('case_id');
            $homevilleDocumentInfo->link = '';
            $homevilleDocumentInfo->doc_type = 'sign_request';
            $homevilleDocumentInfo->save();
        // }

        $this->response = $wrapper;
        return $this;
    }

    public function generateNACHMandate($wrapper)
    {
        if ($this->isError($wrapper)){
            return $this;
        }

        if (isset($wrapper->data)) {
            // Convert object to array to handle properties with spaces
            $data = json_decode(json_encode($wrapper->data), true);
            
            $mandate_link = $data['nach url'] ?? $data['nach_url'] ?? '';
            $current_status = $data['nach status'] ?? $data['nach_status'] ?? 'initiated';

            $homevilleMandate = new HomevilleMandate();
            $homevilleMandate->fill(
                [
                    'application_id' => $this->request->get('id'),
                    'case_id' => $this->request->get('case_id'),
                    'mandate_link' => $mandate_link,
                    'current_status' => $current_status
                ]
            );

            $homevilleMandate->save();

            saveComment("HomeVille Mandate Link: ".$wrapper->data->nach_url, $this->request->get('id'), (Auth::check() ? Auth::user()->id : 107));
        }

        $this->response = $wrapper;
        return $this;
    }

    public function getApplicantBankDetails($wrapper)
    {
        if ($this->isError($wrapper)){
            return $this;
        }

        $this->response = $wrapper;
        return $this;
    }

    public function masterDocumentAPI($wrapper)
    {
        if ($this->isError($wrapper)){
            return $this;
        }

        $this->response = $wrapper;
        return $this;
    }

    public function getFormFields($wrapper)
    {
        if ($this->isError($wrapper)){
            return $this;
        }

        $this->response = $wrapper;
        return $this;
    }

    public function getListOfESign($wrapper)
    {
        if ($this->isError($wrapper)){
            return $this;
        }

        $this->response = $wrapper;
        return $this;
    }

    public function getDocumentId($wrapper)
    {
        if ($this->isError($wrapper)){
            return $this;
        }

        $this->response = $wrapper;
        return $this;
    }

    public function getSolarDetails($wrapper)
    {
        if ($this->isError($wrapper)){
            return $this;
        }

        $this->response = $wrapper;
        return $this;
    }
}