<?php
/*=========================================================================================
    App Name  : PPID PTUN Kupang
    File Name : ActivityLogTrait
    --------------------------------------------------------------------------------------
    Author    : Fuad Auliya Rohman
    Email     : fuad.dev16@gmail.com
==========================================================================================*/

namespace App\Traits;

use App\Models\ActivityLog;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Request;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
use function Illuminate\Events\queueable;

trait ActivityLogTrait
{
    public static function getUserGuard()
    {
        foreach(array_keys(config('auth.guards')) as $guard) {
            if(Auth::guard($guard)->check()) {
                return $guard;
            }
        }
        return null;
    }

    public static function getUserId()
    {
        return Auth::guard(static::getUserGuard())->id();
    }

    public static function getTableName(Model $model)
    {
        return !empty($model->table) ? $model->table : str::lower(Str::snake(Str::pluralStudly(class_basename($model))));
    }

    public static function storeLog($model, $modelPath, $action)
    {
        $newValues = null;
        $oldValues = null;

        if($action === 'CREATED') {
            $newValues = $model->getAttributes();
        } elseif($action === 'UPDATED') {
            $newValues = $model->getChanges();
        }

        if($action !== 'CREATED') {
            $oldValues = $model->getOriginal();
        }

        $activityLog = new ActivityLog();
        $activityLog->method = request()->method();
        $activityLog->type = $modelPath;
        $activityLog->table = static::getTableName($model);
        $activityLog->guard_name = static::getUserGuard();
        $activityLog->activity = $action;
        $activityLog->new_value = !empty($newValues) ? json_encode($newValues) : null;
        $activityLog->old_value = !empty($oldValues) ? json_encode($oldValues) : null;
        $activityLog->ip_address = request()->ip();
        // $activityLog->agent = request()->userAgent();
        $activityLog->causer_id = static::getUserId();
        $activityLog->created_at = getTodayDate();

        $activityLog->save();
    }

    public static function booted()
    {
        // DATA CREATING AND UPDATING EVENT
        static::saved(queueable(function ($model) {
            // CREATE OR UPDATE
            if($model->wasRecentlyCreated) {
                static::storelog($model, static::class, 'CREATED');
            } else {
                if(!$model->getChanges()) {
                    return;
                }
                static::storeLog($model, static::class, 'UPDATED');
            }
        }));

        // DELETE EVENT
        static::deleted(function (Model $model) {
            static::storeLog($model, static::class, 'DELETED');
        });
    }
}
