<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Auth;
use Spatie\Activitylog\Contracts\Activity;
use Spatie\Activitylog\Traits\LogsActivity;

class Collateral extends Model
{
    use SoftDeletes, LogsActivity;

    protected $fillable = [
        'id','cat_id','title','purpose','status'
    ];
    protected $logAttributes = [
        'id','cat_id','title','purpose','status'
    ];
   
    protected static $recordEvents = ['deleted', 'created', 'updated'];
    protected static $logName = 'Collateral Model';
    protected static $logOnlyDirty = true;

    public function getDescriptionForEvent(string $eventName): string
    {
        return "This user has been {$eventName}";
    }

    public function scopeSearch($query,$searchText)
    {
        if(isset($searchText)){
            $query->Title($searchText);
            $query->TitleCategory($searchText);
        }
    }

    public function scopeTitle($query,$searchText)
    {
        return $query->where("title","LIKE","$searchText%");
    }

    public function scopeTitleCategory($query,$searchText)
    {
        return $query->orWhereHas('category',function($query_sub) use ($searchText){
            return $query_sub->where("title","LIKE","$searchText%");
        });
    }

    public function tapActivity(Activity $activity, string $eventName)
    {
        $activity->ip = request()->ip();
        $activity->branch_id = Auth::user()->branch_id;
        $activity->agent = request()->header('user-agent');
    }
    public function category()
    {
        return $this->belongsTo(Category::class,'cat_id');
    }

    public function collateralDetails()
    {
        return $this->hasMany(CollateralDetail::class,'collateral_id');
    }
}
