﻿<?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 Transfer extends Model
{
    protected $fillable = [
        'employee_id',
        'branch_id',
        'department_id',
        'transfer_date',
        'description',
        'created_by',
        'organisation_id',
    ];


    use LogsActivity;

    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()
            ->logAll()
            ->useLogName('transfer')
            ->logOnlyDirty()
            ->setDescriptionForEvent(fn(string $eventName) => " '" . optional($this->employee)->name . "' Transfer has been {$eventName}")
            ->dontSubmitEmptyLogs();
    }

    public function department()
    {
        return $this->hasMany('App\Models\Department', 'id', 'department_id')->first();
    }

    public function branch()
    {
        return $this->hasMany('App\Models\Branch', 'id', 'branch_id')->first();
    }


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

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

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