<?php

namespace App\Trains;

use App\Models\User;
use Illuminate\Support\Facades\Auth;

trait UserTracking
{
    protected static function bootUserTracking()
    {
        // Ketika model dibuat
        static::creating(function ($model) {
            if (Auth::check()) {
                $model->created_by = Auth::id();
                $model->updated_by = Auth::id();
            }
        });

        // Ketika model diupdate
        static::updating(function ($model) {
            if (Auth::check()) {
                $model->updated_by = Auth::id();
            }
        });

        // Ketika model dihapus (soft delete)
        static::deleting(function ($model) {
            if (Auth::check()) {
                $model->deleted_by = Auth::id();
                // Simpan deleted_by sebelum soft delete
                $model->saveQuietly();
            }
        });
    }

    /**
     * Relationship dengan user yang membuat
     */
    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    /**
     * Relationship dengan user yang mengupdate
     */
    public function updater()
    {
        return $this->belongsTo(User::class, 'updated_by');
    }

    /**
     * Relationship dengan user yang menghapus
     */
    public function deleter()
    {
        return $this->belongsTo(User::class, 'deleted_by');
    }

    /**
     * Scope untuk filter berdasarkan creator
     */
    public function scopeCreatedBy($query, $userId)
    {
        return $query->where('created_by', $userId);
    }

    /**
     * Scope untuk filter berdasarkan updater
     */
    public function scopeUpdatedBy($query, $userId)
    {
        return $query->where('updated_by', $userId);
    }

    /**
     * Scope untuk filter berdasarkan deleter
     */
    public function scopeDeletedBy($query, $userId)
    {
        return $query->where('deleted_by', $userId);
    }

    /**
     * Get creator name
     */
    public function getCreatorNameAttribute()
    {
        return $this->creator ? $this->creator->name : 'System';
    }

    /**
     * Get updater name
     */
    public function getUpdaterNameAttribute()
    {
        return $this->updater ? $this->updater->name : 'System';
    }

    /**
     * Get deleter name
     */
    public function getDeleterNameAttribute()
    {
        return $this->deleter ? $this->deleter->name : null;
    }
}
