<?php

namespace App\Models;

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

class AppraisalReview extends Model
{
    protected $fillable = [
        'appraisal_date',
        'employee_id',
        'rating_type_id',
        'status',
        'review_type',
        'created_by',
        'allow_goal_update',
        'organisation_id',
        'final_score',
        'is_flagged',
        'admin_flag_comment',
    ];


    use LogsActivity;

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


    // relations
    public function employee()
    {
        return $this->belongsTo(Employee::class);
    }
    public function ratingType()
    {
        return $this->belongsTo(RatingType::class);
    }
    public function goals()
    {
        return $this->belongsToMany(SimpleGoal::class, 'appraisal_review_goal');
    }
    public function feedback()
    {
        return $this->hasMany(AppraisalReviewFeedback::class);
    }
    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    public function weightedCriteria()
    {
        return $this->hasOne(WeightedCriteria::class);
    }

    public function competencies()
    {
        return $this->belongsToMany(Competencies::class, 'appraisal_review_competency', 'appraisal_review_id', 'competency_id')
            ->withPivot(['weight', 'rating', 'comment', 'organisation_id'])
            ->withTimestamps();
    }

    public function peers()
    {
        return $this->belongsToMany(Employee::class, 'appraisal_review_peers', 'appraisal_review_id', 'employee_id')
            ->withPivot('organisation_id')
            ->withTimestamps();
    }
    public function appraisalFinalScore()
    {
        return $this->hasOne(AppraisalFinalScore::class);
    }
}
