<?php

namespace App\Models;

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

class Employee extends Model
{
    use HasFactory;

    protected $fillable = [
        'nip', 'name', 'email', 'phone', 'department_id', 'position',
        'employment_status', 'join_date', 'retirement_date', 'retirement_type',
        'retirement_document', 'status', 'created_by'
    ];

    protected $casts = [
        'join_date' => 'date',
        'retirement_date' => 'date',
    ];

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

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

    public function accessDetails()
    {
        return $this->hasMany(EmployeeAccessDetail::class);
    }

    public function reminderLogs()
    {
        return $this->hasMany(ReminderLog::class);
    }

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

    public function scopeRetiringSoon($query, $days = 30)
    {
        return $query->where('status', 'retiring')
            ->orWhere(function ($q) use ($days) {
            $q->where('status', 'active')
                ->whereNotNull('retirement_date')
                ->where('retirement_date', '<=', Carbon::now()->addDays((int)$days))
                ->where('retirement_date', '>=', Carbon::now());
        });
    }

    public function daysUntilRetirement()
    {
        if (!$this->retirement_date)
            return null;
        return Carbon::now()->diffInDays($this->retirement_date, false);
    }
}