<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;

class PerformanceEvaluation extends Model
{
    protected $fillable = [
        'eval_number','employee_id','evaluator_id','period_id',
        'total_score','weighted_score','rating',
        'evaluator_comments','employee_comments',
        'development_goals','training_needs','status',
        'submitted_at','acknowledged_at','hr_reviewed_at','completed_at','hr_reviewer_id',
    ];

    protected $casts = [
        'submitted_at'   => 'datetime',
        'acknowledged_at'=> 'datetime',
        'hr_reviewed_at' => 'datetime',
        'completed_at'   => 'datetime',
    ];

    protected static function booted(): void
    {
        static::creating(function ($e) {
            if (! $e->eval_number) {
                $e->eval_number = 'PE-'.date('Y').'-'.str_pad(
                    self::whereYear('created_at', date('Y'))->count() + 1,
                    4, '0', STR_PAD_LEFT
                );
            }
        });
    }

    public function getRatingLabelAttribute(): string
    {
        return match ($this->rating) {
            'excellent'          => 'Excellent',
            'very_good'          => 'Very Good',
            'satisfactory'       => 'Satisfactory',
            'needs_improvement'  => 'Needs Improvement',
            'unsatisfactory'     => 'Unsatisfactory',
            default              => '—',
        };
    }

    public function getRatingBadgeAttribute(): string
    {
        return match ($this->rating) {
            'excellent'          => 'success',
            'very_good'          => 'primary',
            'satisfactory'       => 'info',
            'needs_improvement'  => 'warning',
            'unsatisfactory'     => 'danger',
            default              => 'secondary',
        };
    }

    public function employee()   { return $this->belongsTo(Employee::class); }
    public function evaluator()  { return $this->belongsTo(User::class, 'evaluator_id'); }
    public function period()     { return $this->belongsTo(EvaluationPeriod::class); }
    public function scores()     { return $this->hasMany(EvaluationScore::class, 'evaluation_id'); }
    public function hrReviewer() { return $this->belongsTo(User::class, 'hr_reviewer_id'); }
}
