<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Employee extends Model
{
    use HasUuids, SoftDeletes;

    protected $fillable = [
        'employee_number', 'user_id', 'department_id', 'position_id', 'hire_date',
        'salary', 'bank_account', 'tax_number', 'insurance_number', 'status',
        'manager_id', 'branch_id', 'emergency_contact', 'notes',
        'payroll_expense_account_id', 'payroll_liability_account_id',
    ];

    protected $casts = ['hire_date' => 'datetime', 'emergency_contact' => 'array'];

    public function user()
    {
        return $this->belongsTo(User::class);
    }

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

    public function position()
    {
        return $this->belongsTo(Position::class);
    }

    public function manager()
    {
        return $this->belongsTo(Employee::class, 'manager_id');
    }

    public function subordinates()
    {
        return $this->hasMany(Employee::class, 'manager_id');
    }

    public function branch()
    {
        return $this->belongsTo(Branch::class);
    }

    public function attendanceRecords()
    {
        return $this->hasMany(AttendanceRecord::class);
    }

    public function performanceMetrics()
    {
        return $this->hasMany(PerformanceMetric::class);
    }

    public function performanceReviews()
    {
        return $this->hasMany(PerformanceReview::class);
    }

    public function payrollRecords()
    {
        return $this->hasMany(PayrollRecord::class);
    }

    public function leaveRequests()
    {
        return $this->hasMany(LeaveRequest::class);
    }

    public function trainingRecords()
    {
        return $this->hasMany(TrainingRecord::class);
    }

    public function salaryAdvances()
    {
        return $this->hasMany(SalaryAdvance::class);
    }

    public function getFirstNameAttribute(): string
    {
        $name = trim((string) ($this->user?->name ?? ''));
        if ($name === '') {
            return '';
        }

        return explode(' ', $name)[0];
    }

    public function getLastNameAttribute(): string
    {
        $name = trim((string) ($this->user?->name ?? ''));
        if ($name === '' || ! str_contains($name, ' ')) {
            return '';
        }

        return trim(substr($name, strpos($name, ' ') + 1));
    }

    public function getEmailAttribute(): ?string
    {
        return $this->user?->email;
    }

    public function getPhoneAttribute(): ?string
    {
        return $this->user?->phone;
    }

    public function getJobTitleAttribute(): ?string
    {
        return $this->position?->title;
    }
}
