<?php

namespace App\Http\Middleware;

use App\Log;
use Closure;
use Illuminate\Support\Facades\Auth;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use MongoDB\BSON\Type;

class LogMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $input = $request->all(); //操作的內容
        $path = $request->path();  //操作的路由
        $method = $request->method();  //操作的方法
        $ip = $request->ip();  //操作的IP
        $usernum=null;
        if (!Auth::check()){
            $usernum="訪客";
        }
        else{
            $usernum=$request->user('User')->name;  //操作人(要自己獲取)
        }
        //print(sprintf("當前使用者ID: %s ，log 目前先不寫進資料庫，如果不想顯示此段訊息，或是想寫進資料庫，通知 Bruce",$usernum == 0 ? "訪客" : $usernum));
        if ($method=="POST"){  //只紀錄 POST 的操作，諸如各頁面的CRUD
            self::writeLog($usernum,$input,$path,$method,$ip);
        }

        return $next($request);
    }

    public  function writeLog($usernum,$input,$path,$method,$ip){
//        $log=new Log();
//        $log->setAttribute('Operator', $usernum);
//        $log->setAttribute('Operate_Page', $path);
//        $log->setAttribute('Operate_Type', $method);
//        $log->setAttribute('IP', $ip);
//        $log->setAttribute('Operate_Detail', json_encode($input, JSON_UNESCAPED_UNICODE));
//        $log->save();
        if ($path !='plates/select'){
            $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => 'http://'.env("InfluxDB_IP").'/write?+&db='.env("InfluxDB_DB"),
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => "",
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 0,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => "POST",
                CURLOPT_POSTFIELDS =>"Log,Tag=logs Operator=\"".$usernum."\",Operate_Page=\"".$path."\",Operate_Type=\"".$method."\",IP=\"".$ip."\",Operate_Detail=\"".json_encode($input, JSON_UNESCAPED_UNICODE)."\"",
                CURLOPT_HTTPHEADER => array(
                    "Content-Type: text/plain"
                ),
            ));

            $response = curl_exec($curl);
            curl_close($curl);
            echo $response;
        }
    }
}
