<?php

namespace App\Models\Accounting;

use App\Models\User;
use App\Traits\JsonConvert;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Spatie\Activitylog\Models\Activity;
use Spatie\Activitylog\Traits\LogsActivity;

class Asset extends Model
{
    use HasFactory, SoftDeletes, LogsActivity,JsonConvert;
    protected $table = 'assets';
    protected $fillable = [
        'id','name','desc','created_by','created_at'
    ];
    protected static $logAttributes = [
        'id','name','desc','created_by','created_at'
    ];
    protected static $recordEvents = ['deleted', 'created', 'updated'];
    protected static $logName = 'Asset Model';
    protected static $logOnlyDirty = true;
    public function getDescriptionForEvent(string $eventName): string
    {
        return "This Asset has been {$eventName}";
    }
    public function tapActivity(Activity $activity, string $eventName)
    {
        $activity->ip = request()->ip();
        $activity->agent = request()->header('user-agent');
    }

    public function scopeSearch($query, $searchText)
    {
        if(isset($searchText)){
            $query->name($searchText);
            $query->orWhere("desc","LIKE","$searchText%");
            $query->orWhereHas("createdBy",function($q) use($searchText){
                $q->where("name","LIKE","$searchText%");
            });
        }
        return $query;
    }

    public function scopeName($query, $searchText)
    {
        $query->where("name", "LIKE", "$searchText%");
    }

    public function createdBy()
    {
        return $this->belongsTo(User::class, 'created_by');
    }
}
