<?php

namespace App\Models;

use App\Models\Accounting\ChartOfAccount;
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 Expense extends Model
{
    use HasFactory, SoftDeletes, LogsActivity,JsonConvert;
    protected $table = 'expenses';
    protected $fillable = [
        'id',
        'branch_id',
        'currency_id',
        'chart_of_acc_id',
        'parent_id',
        'invoice_number',
        'payment_model_id',
        'payment_model_type',
        'expense_date',
        'created_by',
        'debit',
        'credit',
        'desc',
        'created_by',
        'deleted_at',
        'created_at',
        'updated_at',
    ];
    protected static $logAttributes = [
        'id',
        'branch_id',
        'currency_id',
        'chart_of_acc_id',
        'parent_id',
        'invoice_number',
        'payment_model_id',
        'payment_model_type',
        'expense_date',
        'created_by',
        'debit',
        'credit',
        'desc',
        'created_by',
        'deleted_at',
        'created_at',
        'updated_at',
    ];

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

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

    public function payment_model()
    {
        return $this->morphTo();
    }

    public function chartOfAcc()
    {
        return $this->belongsTo(ChartOfAccount::class, 'chart_of_acc_id','id');
    }
    public function user()
    {
        return $this->belongsTo(User::class, 'created_by','id');
    }
}
