<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Http\Request;

class GeneralLog extends Model
{
    protected $table = 'tb_general_log';
    protected $primaryKey = 'id';

    public $keyType = 'int';
    public $incrementing = false;
    public $timestamps = false;

    const CREATED_AT = 'created_at';
    const UPDATED_AT = null;
    const DELETED_AT = null;

    protected $guarded = [];

    public function user()
    {
        return $this->belongsTo(User::class)->withDefault();
    }

    /**
     * DB SQL 처리 등록
     */
    public function register(QueryExecuted $query, Request $request): bool
    {
        $request->offsetUnset('_token');

        $gets = $request->getQueryString();
        if ($gets) {
            parse_str($gets, $arr);
            if (array_key_exists('_token', $arr)) {
                unset($arr['_token']);
            }
            $gets = http_build_query($arr);
        }

        $posts = json_encode($request->toArray());
        if($posts === '[]') {
            $posts = null;
        }

        return $this->insert([
            'user_id' => $request->user()?->id,
            'method' => $request->getMethod(),
            'url' => FULL_URL,
            'gets' => $gets,
            'posts' => $posts,
            'sql' => $query->sql,
            'bindings' => implode(", ", $query->bindings),
            'time' => $query->time,
            'referrer' => REFERER,
            'ip_address' => IP_ADDRESS,
            'user_agent' => USER_AGENT,
            'created_at' => now()
        ]);
    }
}
