<?php

namespace App\Models;

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

class Income extends Model
{
    use HasFactory, SoftDeletes, LogsActivity,JsonConvert;
    protected $table = 'incomes';
    protected $fillable = [
        'id',
        'branch_id',
        'currency_id',
        'chart_of_acc_id',
        'parent_id',
        'invoice_number',
        'payment_model_id',
        'payment_model_type',
        'income_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',
        'income_date',
        'created_by',
        'debit',
        'credit',
        'desc',
        'created_by',
        'deleted_at',
        'created_at',
        'updated_at',
    ];

    protected static $recordEvents = ['deleted', 'created', 'updated'];
    protected static $logName = 'Income Model';
    protected static $logOnlyDirty = true;
    public function getDescriptionForEvent(string $eventName): string
    {
        return "This Income 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');
    }
}
