<?php

namespace App\Models;

use Illuminate\Support\Facades\Auth;
use App\Scopes\OrganisationScope;

use Illuminate\Database\Eloquent\Model;
use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Activitylog\LogOptions;

class Expense extends Model
{
    protected $fillable = [
        'account_id',
        'amount',
        'date',
        'income_category_id',
        'payee_id',
        'payment_type_id',
        'transaction_id',
        'referal_id',
        'description',
        'created_by',
        'organisation_id',
    ];

    use LogsActivity;

    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()
            ->logAll()
            ->useLogName('expense')
            ->logOnlyDirty()
            ->setDescriptionForEvent(fn(string $eventName) => " ID #{$this->id} Expense has been {$eventName}")
            ->dontSubmitEmptyLogs();
    }

    public function account($account)
    {
        $account = AccountList::where('id', '=', $account)->first();
        return $account;
    }
    public static function payee($payee)
    {
        $payee = Payees::where('id', '=', $payee)->first();
        return $payee;
    }

    public function expense_category($category)
    {
        $category = ExpenseType::where('id', '=', $category)->first();

        return $category;
    }

    public function payment_type($payment)
    {
        $payment = PaymentType::where('id', '=', $payment)->first();
        return $payment;
    }

    public function accounts()
    {
        return $this->hasOne('App\Models\AccountList', 'id', 'account_id');
    }

    public function payees()
    {
        return $this->hasOne('App\Models\Payees', 'id', 'payee_id');
    }

    public function employee_payees()
    {
        return $this->hasOne('App\Models\Employee', 'id', 'payee_id');
    }

    public function expense_categorys()
    {
        return $this->hasOne('App\Models\ExpenseType', 'id', 'expense_category_id');
    }

    public function payment_types()
    {
        return $this->hasOne('App\Models\PaymentType', 'id', 'payment_type_id');
    }

    protected static function booted()
    {
        static::addGlobalScope(new OrganisationScope);

        static::creating(function ($model) {
            if (Auth::check()) {
                $model->organisation_id = Auth::user()->organisation_id;
            }
        });
    }
}
