<?php
/**
 * Created by PhpStorm.
 * User: sunil
 * Date: 28/11/18
 * Time: 12:39 PM
 */

namespace App;


use App\Events\V1\EventPostBureauPull;
use App\Events\V1\EventPostCSBureauBankPull;
use App\Http\Middleware\MongoMiddleware;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use App\Logging\CloudWatchLoggerFactory;

class BankValidation
{
    private $request;
    private $endPointDevelopment = '';
    private $fileURL = '';
    private $karza_key = '';
    private $production = 'SFXdlWrNYduYwxk';
    private $curl;
    private $link;
    private $s3 = null;
    private $filePath;
    const PUBLIC = 'public';
    const PRIVATE = 'private';
    private $response;
    private $start_time;
    private $payload;

    public function __construct(Request $request){
        // (new Slack(new Request(['title' => 'into validation', 'fields' => ['application_id' => '123'], 'group' => Slack::$STAGE_TESTING])))->send();
        $this->request = $request;
        $this->data = ($this->request->has('data')) ? $this->request->get('data') : false;
        $this->endPointDevelopment = (_env('KARZAURL', '')).'bankacc';
        $this->endPointDevelopmentv3 = (_env('KARZAURLV3', '')).'bankacc-verification';
        $this->karza_key = (_env('KARZAKEY', ''));
        $this->version = (_env('KARZA_BANK_VERSION', ''));
        $this->start_time = time();
        // (new Slack(new Request(['title' => 'url & key', 'fields' => ['url' => $this->endPointDevelopment, 'key' => $this->karza_key, 'version' => $this->version], 'group' => Slack::$STAGE_TESTING])))->send();
        if($this->endPointDevelopment && $this->karza_key) {
            (new Slack(new Request(['title' => 'karza url key check', 'fields' => ['application_id' => '123'], 'group' => Slack::$STAGE_TESTING])))->send();
            if ($this->request->has('validateEmail')){
                $this->startEmailValidation();
            }else{
                if ($this->version == '3') {
                    $this->setupv3();
                } else {
                    $this->setup();
                }
            }
        }
    }

    private function setup(){
        // (new Slack(new Request(['title' => 'in setup', 'fields' => ['application_id' => '123'], 'group' => Slack::$STAGE_TESTING])))->send();
        $this->payload = json_encode($this->data);

        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $this->endPointDevelopment,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => $this->payload,
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json',
                'cache-control: no-cache',
                'x-karza-key: '.$this->karza_key
            ),
        ));

        $this->curl = $curl;
    }

    private function setupv3(){
        $this->payload = json_encode($this->data);

        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $this->endPointDevelopmentv3,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => $this->payload,
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json',
                'cache-control: no-cache',
                'x-karza-key: '.$this->karza_key
            ),
        ));

        $this->curl = $curl;
    }


    public function get(){
        try {
            // (new Slack(new Request(['title' => 'bank validation api call completed', 'fields' => ['application_id' => '123'], 'group' => Slack::$STAGE_TESTING])))->send();
            $response = curl_exec($this->curl);
            if (curl_error($this->curl)) {
                $error = curl_error($this->curl);
            }
            curl_close($this->curl);
            // (new Slack(new Request(['title' => 'validation triggered', 'fields' => ['application_id' => '123'], 'group' => Slack::$STAGE_TESTING])))->send();
            $cwFactory = new CloudWatchLoggerFactory();
            if ($this->version == '3') {
                $data = array('user_id'=> Auth::user()->id, 'vendor'=> 'Karza', 'api_url' => $this->endPointDevelopmentv3,'Request'=> $this->payload ?? '{}', 'Response'=>json_decode($response, 1) ?? '', 'error_msg' => isset($error) ? json_decode($error, 1) : '');
                $cwFactory->logger(json_encode($data));
            } else {
                $data = array('user_id'=> Auth::user()->id, 'vendor'=> 'Karza', 'api_url' => $this->endPointDevelopment,'Request'=> $this->payload ?? '{}', 'Response'=>json_decode($response, 1) ?? '', 'error_msg' => isset($error) ? json_decode($error, 1) : '');
                $cwFactory->logger(json_encode($data));
            }

            $mongo = new MongoMiddleware();
            $mongo->toMongo($this->request, new Response(['data' => $response, 'error' => isset($error) ? $error : null]));

            (new Services())->log('Karza', ['status' => true, 'service_count' => 0, 'start_time' => $this->start_time]);

            if (isset($error)) {
                return false;
            }
            $data = json_decode($response, 1);

            if (isset($data->result->accountName) && isset($this->data['name'])) {
                $percentage = 0;
                $compare = isset($item->accountName) ? similar_text(strtolower($this->data['name']), strtolower($data->result->accountName), $percentage) : 0;
                if ($percentage < 40) {
                    $this->addComment();
                }
            }

            if (isset($data)) {
                return $data;
            } else {
                return false;
            }
        }catch (\Exception $e){
            (new Slack(new Request(['title' => 'bank validation exception', 'fields' => ['message' => $e->getMessage(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString()], 'group' => Slack::$STAGE_TESTING])))->send();
        }
        return false;
    }

    public function startEmailValidation(){
        $this->data = ['email' => $this->request->get('email')];
        $this->endPointDevelopment = _env('KARZAURLDOMAIN').'email';
        $this->setup();
        $this->response = $this->get();
    }

    public function validateEmail(){
        if (isset($this->response['result']['data']['result'])){
            return array('response' => json_encode($this->response), 'status' => $this->response['result']['data']['result'] ? 1 : 0);
        }

        return array('response' => json_encode($this->response), 'status' => 0);
    }

    public function addComment(){
        $comment = new Comments();
        $comment->application_id = $this->data['application_id'];
        $comment->user_id = Auth::user()->id;
        $comment->comment = 'Name Matching is less than 40% with '.$this->data['name'];
        $comment->show_merchant = 0;
        $comment->show_consumer = 0;
        $comment->save();
    }
}
