<?php

namespace Base;

use Base\Tables\SystemLogs;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;

class Logs
{
    protected $request, $data, $type, $endpoint;

    public function __construct($data, $type){
        $this->request = $data;
        $this->type = $type;
        $this->endpoint = request()->path();
    }

    public function addLog() : string {
        $data = $this->parseData();
        $logs = new SystemLogs();
        $logs->user_id = $data['user'];
        $logs->endpoint = $data['endpoint'];
        $logs->type = $data['type'];
        $logs->value = json_encode($data['value']);
        $logs->save();
        $this->createLog();
        return "Log created";
    }

    private function parseData() : array {
        $data = $this->request;
        $response['user'] = Auth::user() ? Auth::user()->id : 0;
        $response['type'] = $this->type;
        $response['endpoint'] = $this->endpoint ?? null;
        if($this->type === 'request'){
            if(isset($data['username'])) $response['value'] = "System Login: ".$data['username'];
            else $response['value'] = $data;
        }
        else if($this->type === 'response'){
            $response['value'] = $data;
        }
        return $response;
    }


    private function createLog() {
//        $logCount = SystemLogs::query()->select()->count();
//        $logFile = '';
//        if($logCount > 50){
//            $logs = SystemLogs::query()->select()->get();
//            foreach($logs as $log){
//                $file = $log->created_at.' | '.$log->user_id.' | '.$log->type.' | '.$log->endpoint.' | '.$log->value.' '.PHP_EOL;
//                $logFile = $logFile.$file;
//            }
//            file_put_contents(public_path()."/tmp/Log_".date('Y-m-d H:i:s'), $logFile);
//            SystemLogs::query()->truncate();
//        }
    }
}
