<?php


namespace App\Models;

use App\Scopes\OrganisationScope;
use Illuminate\Support\Facades\Auth;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Activitylog\LogOptions;

class SimpleGoal extends Model
{
    use HasFactory;

    protected $fillable = [
        'organisation_id',
        'title',
        'description',
        'start_date',
        'due_date',
        'status',
        'is_visible_to_employee',
        'weight',
        'is_active'
    ];

    protected $casts = [
        'start_date'              => 'date',
        'due_date'                => 'date',
        'is_visible_to_employee'  => 'boolean',
    ];

    use LogsActivity;

    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()
            ->logAll()
            ->useLogName('simple_goal')
            ->logOnlyDirty()
            ->setDescriptionForEvent(fn(string $eventName) => "{$this->title} Goal has been {$eventName}")
            ->dontSubmitEmptyLogs();
    }


    /* Relationships */
    public function organisation()
    {
        return $this->belongsTo(Organisation::class);
    }

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

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

    public function employees()
    {
        return $this->belongsToMany(
            Employee::class,
            'simple_goal_employees',      // pivot table
            'simple_goal_id',            // FK to SimpleGoal in pivot
            'employee_id'
        )
            ->withTimestamps();
    }

    public function appraisalFeedback()
    {
        return $this->hasMany(AppraisalReviewFeedback::class);
    }
}
