<?php

namespace App\Models;

use Database\Factories\UserFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    /** @use HasFactory<UserFactory> */
    use HasFactory, Notifiable;

    protected $fillable = [
        'surname',
        'firstname',
        'othername',
        'email',
        'ippis_no',
        'phone',
        'designation',
        'staff_number',
        'avatar',
        'role',
        'department_id',
        'supervisor_id',
        'counter_signing_officer_id',
        'is_active',
        'password',
    ];

    protected $hidden = [
        'password',
        'remember_token',
    ];

    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
            'is_active' => 'boolean',
        ];
    }

    // ── Accessors ──────────────────────────────────

    public function getFullNameAttribute(): string
    {
        return trim("{$this->surname} {$this->firstname} {$this->othername}");
    }

    public function getInitialsAttribute(): string
    {
        $first = $this->firstname ? mb_substr($this->firstname, 0, 1) : '';
        $last = $this->surname ? mb_substr($this->surname, 0, 1) : '';
        return strtoupper($first . $last);
    }

    public function getRoleLabelAttribute(): string
    {
        return match ($this->role) {
            'admin' => 'Administrator',
            'director' => 'Director',
            'department_head' => 'Head of Department',
            'supervisor' => 'Supervisor',
            'staff' => 'Staff',
            default => ucfirst($this->role),
        };
    }

    // ── Role Checks ────────────────────────────────

    public function isAdmin(): bool
    {
        return $this->role === 'admin';
    }

    public function isDirector(): bool
    {
        return $this->role === 'director';
    }

    public function isDepartmentHead(): bool
    {
        return $this->role === 'department_head';
    }

    public function isSupervisor(): bool
    {
        return $this->role === 'supervisor';
    }

    public function isStaff(): bool
    {
        return $this->role === 'staff';
    }

    public function hasAnyRole(array $roles): bool
    {
        return in_array($this->role, $roles);
    }

    // ── Relationships ──────────────────────────────

    public function department(): BelongsTo
    {
        return $this->belongsTo(Department::class);
    }

    public function supervisor(): BelongsTo
    {
        return $this->belongsTo(User::class, 'supervisor_id');
    }

    public function counterSigningOfficer(): BelongsTo
    {
        return $this->belongsTo(User::class, 'counter_signing_officer_id');
    }

    public function resolveCounterSigningOfficer(): ?User
    {
        if ($this->counter_signing_officer_id && $this->counterSigningOfficer) {
            return $this->counterSigningOfficer;
        }
        if ($this->supervisor && $this->supervisor->supervisor_id) {
            return $this->supervisor->supervisor;
        }
        if ($this->department && $this->department->head_id && $this->department->head_id !== $this->id && $this->department->head_id !== $this->supervisor_id) {
            return $this->department->head;
        }
        return $this->department?->director;
    }

    public function subordinates(): HasMany
    {
        return $this->hasMany(User::class, 'supervisor_id');
    }

    public function appraisals(): HasMany
    {
        return $this->hasMany(Appraisal::class, 'employee_id');
    }

    public function supervisedAppraisals(): HasMany
    {
        return $this->hasMany(Appraisal::class, 'supervisor_id');
    }

    public function counterSignedAppraisals(): HasMany
    {
        return $this->hasMany(Appraisal::class, 'counter_signing_officer_id');
    }

    public function developmentPlans(): HasMany
    {
        return $this->hasMany(DevelopmentPlan::class, 'employee_id');
    }

    public function sentFeedback(): HasMany
    {
        return $this->hasMany(Feedback::class, 'from_user_id');
    }

    public function receivedFeedback(): HasMany
    {
        return $this->hasMany(Feedback::class, 'to_user_id');
    }

    // ── Scopes ─────────────────────────────────────

    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    public function scopeByRole($query, string $role)
    {
        return $query->where('role', $role);
    }

    public function scopeInDepartment($query, int $departmentId)
    {
        return $query->where('department_id', $departmentId);
    }
}
