<?php
/**
 * Created by PhpStorm.
 * User: sunilkhorwal
 * Date: 2019-05-30
 * Time: 15:57
 */

namespace App\Avanse\Logging;

use App\AvanseRequests;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Config;
use Carbon\Carbon;
use App\Slack;

class Logging{

    protected $request;
    protected $payload;
    protected $api;
    protected $service;
    protected $messageID;
    protected $serviceAttributes;
    protected $response = null;
    protected $headers;
    private $start_time;
    protected $getService;

    public function __construct(Request $request){
        $this->request = $request;
        $this->start_time = Carbon::now()->toDateTimeString();
    }

    protected function initialize(){
        $this->serviceAttributes = Config::get('avanse');
        $base = $this->serviceAttributes['base'];
        if (!empty($this->serviceAttributes['services'][$this->getService])) {
            $this->service = $this->serviceAttributes['services'][$this->getService];
        }

        if (!empty($this->service['API'])) {
            $this->api = $base.$this->service['API'];
        }

        if ($this->getService == 'callBRE'){
            $this->api = $this->service['API'];
        }

        $this->messageID = 'CF|'.$this->request->get('id').'|'.time();
    }

    protected function logging() {

        $this->dbLogging();

        // Only on local and testing, not on production
        if(_env("APP_CONNECTION") == 0) {
            //$this->fileLogging();
        }
        //$this->fileLogging();
        if ($this->response && isset($this->response->status)){
            (new Slack(new Request(['title' => $this->getService . ' Error', 'fields' => ['response' => $this->response, 'request' => json_encode($this->request->all())]])))->send();
            return false;
        }
        return true;
    }

    private function fileLogging()
    {
        $log = [
            'request' => $this->payload,
            'response' => $this->response,
            'headers' => $this->headers
        ];
        $date = Carbon::now()->toDateString();

        $base = storage_path() . '/avanse';

        if (!file_exists($base)) {
            mkdir($base, 0777, true);
        }

        if (!file_exists($base . '/' . $date)) {
            mkdir($base . '/' . $date, 0777, true);
        }
        $fileName = time() . '_' . $this->service['ServiceName'] . '_' . $this->messageID . '.json';
        if (file_exists($base . '/' . $date . '/' . $fileName)){
            $file = fopen($base . '/' . $date . '/' . $fileName, "w") or die("Unable to open file!");
            fwrite($file, json_encode($log));
            fclose($file);
        }

    }

    private function dbLogging(){
        try {


            $time = Carbon::now()->toDateTimeString();

            $avanseRequests = new AvanseRequests();

            $avanseRequests->fill(
                [
                    'message_id' => $this->messageID,
                    'application_id' => $this->request->get('id'),
                    'api' => $this->api,
                    'request' => json_encode($this->payload),
                    'response' => $this->response,
                    'headers' => json_encode($this->headers),
                    'start_time' => $this->start_time,
                    'end_time' => $time,
                    'user_id' => Auth::check() ? Auth::user()->id : 107,
                    'created_at' => $time,
                ]
            );
            $avanseRequests->save();

        }catch (\Exception $e){
            (new Slack(new \Illuminate\Http\Request(['title' => 'API Logging Catch', 'fields' => ['Status' => 'API Logging','F' => $e->getFile(), 'L' => $e->getLine(), 'M' => $e->getMessage(), 'T' => $e->getTraceAsString()], 'group' => Slack::$AVANSE_DISBURSEMENT])))->send();
        }
    }
}
