<?php

namespace App\Models\Accounting;

use App\Models\User;
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 ChartOfAccount extends Model
{
    use HasFactory, SoftDeletes, LogsActivity;
    protected $table = 'chart_of_accounts';
    protected $fillable = [
        'id',
        'type_of_acc_detail_id',
        'chart_code',
        'chart_name',
        'desc',
        'created_by',
        'payment',
        'deleted_at',
        'created_at',
        'updated_at',
    ];
    protected static $logAttributes = [
        'id',
        'type_of_acc_detail_id',
        'chart_code',
        'chart_name',
        'desc',
        'created_by',
        'payment',
        'deleted_at',
        'created_at',
        'updated_at',
    ];

    protected static $recordEvents = ['deleted', 'created', 'updated'];
    protected static $logName = 'ChartOfAccount Model';
    protected static $logOnlyDirty = true;
    public function getDescriptionForEvent(string $eventName): string
    {
        return "This ChartOfAccount 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->ChartName($searchText);
            $query->orWhere("chart_code","LIKE","$searchText%");
            $query->orWhereHas("typeAccDetails",function($q) use($searchText){
                $q->where("name","LIKE","$searchText%");
            });
            $query->orWhereHas("createdBy",function($q) use($searchText){
                $q->where("name","LIKE","$searchText%");
            });
        }
        return $query;
    }

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

    public function typeAccDetails()
    {
        return $this->belongsTo(TypeOfAccDetail::class, 'type_of_acc_detail_id');
    }

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