<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;

class Employee extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'employee_id',
        'full_name',
        'full_name_ar',
        'photo',
        'nationality',
        'gender',
        'date_of_birth',
        'marital_status',
        'email',
        'phone',
        'phone_2',
        'address',
        'emergency_contact_name',
        'emergency_contact_phone',
        'emergency_contact_relationship',
        'department_id',
        'designation_id',
        'reporting_manager_id',
        'employment_type',
        'joining_date',
        'probation_period_days',
        'confirmation_date',
        'status',
        'termination_date',
        'termination_reason',
        'user_id',
    ];

    protected $casts = [
        'date_of_birth' => 'date',
        'joining_date' => 'date',
        'confirmation_date' => 'date',
        'termination_date' => 'date',
    ];

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

    public function designation()
    {
        return $this->belongsTo(Designation::class);
    }

    public function reportingManager()
    {
        return $this->belongsTo(User::class, 'reporting_manager_id');
    }

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

    public function documents()
    {
        return $this->hasMany(EmployeeDocument::class);
    }

    public function attendances()
    {
        return $this->hasMany(Attendance::class);
    }

    public function leaveApplications()
    {
        return $this->hasMany(LeaveApplication::class);
    }

    public function salaryStructures()
    {
        return $this->hasMany(SalaryStructure::class);
    }

    public function currentSalary()
    {
        return $this->hasOne(SalaryStructure::class)->where('is_active', true)->latest();
    }

    public function payrolls()
    {
        return $this->hasMany(Payroll::class);
    }

    // Helper Methods
    public static function generateEmployeeId()
    {
        $lastEmployee = self::orderBy('id', 'desc')->first();
        $number = $lastEmployee ? ((int) substr($lastEmployee->employee_id, 3)) + 1 : 1;
        return 'EMP' . str_pad($number, 5, '0', STR_PAD_LEFT);
    }

    public function getAgeAttribute()
    {
        return $this->date_of_birth ? $this->date_of_birth->age : null;
    }

    public function getTenureAttribute()
    {
        return $this->joining_date ? $this->joining_date->diffInYears(now()) : null;
    }
}
