<?php
/**
 * Created by PhpStorm.
 * User: sarah z
 * Date: 26/02/18
 * Time: 11:00 PM
 */

namespace App;


use App\Http\Controllers\Admin\ConsumerDocument;
use Barryvdh\DomPDF\Facade as PDF;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Storage;

class finBoxIntegration extends Model
{
    private $finbox_url = '';
    private $finbox_hash = '';
    private $finbox_version = '';
    private $finbox_server_key = '';
    private $webhook_response_fetch = '';
    private $curl;
    private $payload;


    public function setup(){
        $this->finbox_url = (_env('FINBOX_URL', ''));
        $this->finbox_hash = (_env('FINBOX_CLIENT_SECRET', ''));
        $this->finbox_server_key = (_env('FINBOX_SERVER_KEY', ''));
        $this->webhook_response_fetch = 'https://insights.finbox.in/v2/risk/predictors?source=webhook&request_id=';
        $this->finbox_version = '4';
    }

    public function getInsights($customer_id){
        $this->setup();
        if($this->finbox_url) {
            $url =$this->finbox_url.'risk/predictors';
            $this->payload = json_encode(['customer_id' => $customer_id, 'version' => $this->finbox_version,
                'salt' => base64_encode(hex2bin(hash('sha256', (strtoupper(md5($customer_id)).$this->finbox_hash))))]);

            $this->callCurl($url, "POST");

            $response = $this->get();

            (new \App\Slack(new Request(['title'=>'API FinBox - response', 'fields'=>['value' => json_encode($response)]])))->send();
            if(isset($response['status']) && $response['status'] === 'complete') {
                $this->saveFinBoxInfo($response, $customer_id);
            }
            return 'true';
        }

        return false;
    }

    public function getWebHookResponse($customer_id, $request_id){
        $this->setup();
//        $url = 'https://insights.finbox.in/staging/risk/predictors?source=webhook&request_id='.$request_id;
        $url = 'https://insights.finbox.in/v2/risk/predictors?source=webhook&request_id='.$request_id;

        $this->payload = json_encode(['customer_id' => $customer_id, 'version' => $this->finbox_version,
            'salt' => base64_encode(hex2bin(hash('sha256', (strtoupper(md5($customer_id)).$this->finbox_hash))))]);

        $this->callCurl($url, "POST");

        $response = $this->get();

        (new \App\Slack(new Request(['title'=>'Webook FinBox - Response', 'fields'=>['value' => json_encode($response)]])))->send();
        if(isset($response['status']) && $response['status'] === 'complete') {
            $this->saveFinBoxInfo($response, $customer_id);
        }
        return 'true';
    }

    public function saveFinBoxInfo($response, $customer_id){
        (new \App\Slack(new Request(['title'=>'FinBox Webhook Response - Saved', 'fields'=>['value' => $customer_id]])))->send();
        if (!file_exists(storage_path().'/finBox_info')) {
            mkdir(storage_path().'/finBox_info', 0777, true);
        }

        if (!file_exists(storage_path().'/finBox_info/'.$customer_id)) {
            mkdir(storage_path().'/finBox_info/'.$customer_id, 0777, true);
        }

        if (!file_exists(storage_path().'/finBox_info/'.$customer_id.'/'.Carbon::now()->toDateString())) {
            mkdir(storage_path().'/finBox_info/'.$customer_id.'/'.Carbon::now()->toDateString(), 0777, true);
        }

        $myfile = fopen(storage_path().'/finBox_info/'.$customer_id.'/'.Carbon::now()->toDateString().'/'.time().'.json', "w") or die("Unable to open file!");
        $txt = json_encode($response);
        $encrypted_file = wall_encrypt($txt);
        $encrypted_file = /*$encrypted_file ? $encrypted_file :*/ $txt;
        fwrite($myfile, $encrypted_file);
        fclose($myfile);
    }

    public function get(){
        try {
            $response = curl_exec($this->curl);
            if (curl_error($this->curl)) {
                $error = curl_error($this->curl);
            }
            curl_close($this->curl);


            if (isset($error)) {
                return $error;
            }

            return json_decode($response, 1);

        }catch (\Exception $e){

        }
        return false;
    }

    public function callCurl($url, $method){

        (new \App\Slack(new Request(['title'=>'FinBox - Request', 'fields'=>['url' => $url, 'method' => $method, 'payload' => $this->payload, 'x-api-key' => $this->finbox_server_key]])))->send();

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

        return $this->curl = $curl;
    }
}
