<?php

namespace App\Method\Lendbox\Response;

use App\Http\Controllers\Admin\ConsumerApplicationController;
use App\Method\Lendbox\Helpers\LendboxHelper;
use App\LendboxBorrowerReg;
use App\LendboxCreateLoan;
use App\LenboxLspRepayments;
use App\LendboxDocument;
use App\APIWrapper\Wrapper;
use App\Method\Lendbox\LendboxMethods;
use App\ConsumerApplicationElement;
use App\PaymentTransaction;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rules\In;
use Illuminate\Support\Carbon;
use App\Slack;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;

class Response implements LendboxHelper
{
    public $errorBag;
    public $response;
    public $responseData;
    public function resolveResponse($func, $res, $request = null){
        if(method_exists($this, $func)){
            return $this->$func($res);
        }
        return array();
    }

    public function borrowerRegistration($res){
        (new Slack(new Request(['title'=>"Borrower registration Response", 'fields'=>['Message' => json_encode($res)]])))->send();
        if(isset($res->success) && $res->success != 1){
            $this->errorBag['Error'] = $res->msg;
            $this->response = $res;
            return $this;
        }
        if(isset($res->error->description)){
            $this->errorBag['Error'] = $res->error->description;
            $this->response = $res;
            return $this;
        }

        try{
            $lendbox = LendboxBorrowerReg::where('application_id', Input::get('id'))->first(['id']);
            if (!isset($lendbox->id)){
                $result = 'failure';
                if($res->success == 1){
                    $result = 'success';
                }
                LendboxBorrowerReg::insert([
                    'application_id' => Input::get('id'),
                    'result' => $result,
                    'lbUserId' => $res->data->lbUserId,
                    'user_id' =>Input::get('user_id'),
                    'created_at' =>Carbon::now()->toDateTimeString(),
                    'updated_at' =>Carbon::now()->toDateTimeString()
                ]);
            }
        }catch (\Exception $e){
            (new Slack(new Request(['title'=>'lendbox borrower registration issue','fields'=>['error'=>$e->getMessage(),'line'=>$e->getLine(),'trace'=>$e->getTraceAsString()]])))->send();
        }
        return $this->response = $res;
    }

    public function uploadDocument($res){
        if(isset($res->success) && $res->success == false){
            $this->errorBag['Error'] = $res->msg;
            $this->response = $res;
            return $this;
        }
        if (isset($res->error->description)){
            $this->errorBag['Error'] = $res->error->description;
            $this->response = $res;
            return $this;
        }
        try{
            $LendboxDocuments = new LendboxDocument();
            $lenboxDoc = LendboxDocument::where('consumer_application_file_id',Input::get('file_id'))->count();
            if($lenboxDoc == 0){
                $LendboxDocuments->fill([
                    'application_id' => Input::get('id'),
                    'consumer_application_file_id' => Input::get('file_id'),
                    'response' => json_encode($res),
                    'status' => $res->msg,
                    'user_id' => Input::get('user_id'),
                    'created_at' =>Carbon::now()->toDateTimeString(),
                    'updated_at' =>Carbon::now()->toDateTimeString()
                ]);
                $LendboxDocuments->save();
            }else{
                $update = [
                    'response' => json_encode($res),
                    'status' => $res->msg,
                    'user_id' => Input::get('user_id'),
                    'updated_at' =>Carbon::now()->toDateTimeString()
                ];
                LendboxDocument::where('consumer_application_file_id',Input::get('file_id'))->update($update);
            }
        }catch (\Exception $e){
            (new Slack(new Request(['title'=>'lendbox upload document issue','fields'=>['error'=>$e->getMessage(),'line'=>$e->getLine(),'trace'=>$e->getTraceAsString()]])))->send();
        }
        return $this->response = $res;
    }


    public function createLoan($res){
        (new Slack(new Request(['title'=>"Create Loan Response", 'fields'=>['Message' => json_encode($res)]])))->send();
        if(isset($res->success) && $res->success != 1){
            $this->errorBag['Error'] = $res->msg;
            $this->response = $res;
            return $this;
        }

        if(isset($res->error->description)){
            $this->errorBag['Error'] = $res->error->description;
            $this->response = $res;
            return $this;
        }
        try{
            $lendboxCreateLoan = LendboxCreateLoan::where('application_id', Input::get('id'))->first(['id']);
            if(!isset($lendboxCreateLoan->id)){
                $result = 'failure';
                if($res->success == 1){
                    $result = 'success';
                }
            
                $lendbox = LendboxBorrowerReg::where('application_id', Input::get('id'))->first(['lbUserId']);
                if(isset($lendbox->lbUserId) || Input::get('lbUserId') != ""){
                    LendboxCreateLoan::insert([
                        'application_id' => Input::get('id'),
                        'lbUserId' => isset($lendbox->lbUserId) ? $lendbox->lbUserId : Input::get('lbUserId'),
                        'lbLoanId' =>$res->data->lbLoanId,
                        'result' => $result,
                        'created_at' =>Carbon::now()->toDateTimeString(),
                        'updated_at' =>Carbon::now()->toDateTimeString(),
                        'user_id' =>Input::get('user_id')
                    ]);
                }
            }
        }catch (\Exception $e){
            (new Slack(new Request(['title'=>'lendbox Create loan issue','fields'=>['error'=>$e->getMessage(),'line'=>$e->getLine(),'trace'=>$e->getTraceAsString()]])))->send();
        }
            
        return $this->response = $res;
    }

    public function saveEMI($res){
        (new Slack(new Request(['title'=>"Save EMI Response", 'fields'=>['Message' => json_encode($res)]])))->send();
        
        if(isset($res->success) && $res->success != 1){
            $this->errorBag['Error'] = $res->msg;
            $this->response = $res;
            return $this;
        }

        if(isset($res->error->description)){
            $this->errorBag['Error'] = $res->error->description;
            $this->response = $res;
            return $this;
        }
        
        try{
            if(isset($res->success) && $res->success == 1 && $res->msg == 'EDI Saved Successfully!'){
                LendboxCreateLoan::where('application_id', Input::get('id'))->update(['lbEdiStatus' => 'success']);       
            }
        }catch (\Exception $e){
            (new Slack(new Request(['title'=>'lendbox Save EMi status update issue','fields'=>['error'=>$e->getMessage(),'line'=>$e->getLine(),'trace'=>$e->getTraceAsString()]])))->send();
        }

        return $this->response = $res;
    }

    public function walletOrder($res){
        (new Slack(new Request(['title'=>"Wallet Order Response", 'fields'=>['Message' => json_encode($res)]])))->send();
        if(isset($res->success) && $res->success != 1){
            $this->errorBag['Error'] = $res->msg;
            $this->response = $res;
            return $this;
        }

        if(isset($res->error->description)){
            $this->errorBag['Error'] = $res->error->description;
            $this->response = $res;
            return $this;
        }
        
        try{
            if(Input::get('txnType') == 'DEBIT' && isset($res->success) && $res->success == 1){
                LendboxCreateLoan::where('application_id', Input::get('id'))->update(['lbOrderStatus' => 'success']);       
            }else if(Input::get('txnType') == 'CREDIT' && isset($res->success) && $res->success == 1){
                $lbOrders = isset($res->data) && isset($res->data->processed) ? $res->data->processed->orders : [];
                if(is_array($lbOrders) && count($lbOrders) > 0){
                    $lbOrders = json_decode(json_encode($lbOrders),true);
                    LenboxLspRepayments::insert($lbOrders);
                }
            }
        }catch (\Exception $e){
            (new Slack(new Request(['title'=>'lendbox wallet order status update issue','fields'=>['error'=>$e->getMessage(),'line'=>$e->getLine(),'trace'=>$e->getTraceAsString()]])))->send();
        }

        return $this->response = $res;
    }

    public function transactionStatus($res){
        (new Slack(new Request(['title'=>"Transaction Status Response", 'fields'=>['Message' => json_encode($res)]])))->send();
        if(isset($res->success) && $res->success != 1){
            $this->errorBag['Error'] = $res->msg;
            $this->response = $res;
            return $this;
        }

        if(isset($res->error->description)){
            $this->errorBag['Error'] = $res->error->description;
            $this->response = $res;
            return $this;
        }

        if(isset($res->httpcode) && $res->httpcode != 200){
            $this->errorBag['Error'] = isset($res->msg) ? $res->msg : "Something went wrong";
            $this->response = $res;
            return $this;
        }
        
        try{
            $table = $tableResponse = '';
            if(isset($res->data->txStatus)){
                foreach($res->data->txStatus as $txn){            
                    if(isset($txn->txType) && $txn->txType == 'DEBIT' && $txn->status == 'SUCCESS'){
                        $application_id = str_replace("D","",$txn->txId);
                        ConsumerApplicationElement::where('application_id', $application_id)->update(['reference_number' => $txn->utr]);
                        $application = new ConsumerApplicationController();
                        $application->webhook($application_id, ['status' => 'utr', 'type' => 'UTR-Webhook', 'data' => $application->getMConnectPayload($application_id, 'utr', ['utr' => $txn->utr])]);
                        (new ConsumerApplicationController())->updateApplicationStatus(str_replace("D","",$txn->txId), 'disbursed');
                    }

                    $table .= '<tr>
                        <td width="10%">' . str_replace("D","",$txn->txId) . '</td>
                        <td width="10%">' . $txn->lbUserId . '</td>
                        <td width="10%">' . $txn->amount . '</td>
                        <td width="10%">' . $txn->principal . '</td>
                        <td width="10%">' . $txn->interest . '</td>
                        <td width="10%">' . $txn->txId . '</td>
                        <td width="10%">' . $txn->txType . '</td>
                        <td width="10%">' . $txn->status . '</td>
                        <td width="10%">' . $txn->utr . '</td>
                        <td width="10%">' . $txn->comment . '</td>
                    </tr>';
                }
            }

            if($table){
                $tableResponse = '<p style="text-align:center;margin-top: 15px;"><strong>Lendbox LSP transactions status fetched successfully</strong></p><table border="1" width="100%"><tr><th width="10%">AppId</th><th width="10%">LbUserId</th><th width="10%">Amount</th><th width="10%">Principal</th><th width="10%">Interest</th><th width="10%">TxId</th><th width="10%">TxType</th><th width="10%">Status</th><th width="10%">UTR</th><th width="10%">comment</th></tr>' . $table .'</table>';
            }
        }catch (\Exception $e){
            (new Slack(new Request(['title'=>'lendbox transaction status update issue','fields'=>['error'=>$e->getMessage(),'line'=>$e->getLine(),'trace'=>$e->getTraceAsString()]])))->send();
        }

        $this->responseData = $tableResponse;
        $this->response = $res;
        return $this;
    }


}