<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Staff extends Model
{
    use HasFactory, SoftDeletes;

    protected $table = 'staff';

    protected $guarded = ['id'];

    protected $casts = [
        'has_passport'    => 'boolean',
        'has_epass'       => 'boolean',
        'passport_expiry' => 'date',
        'permit_expiry'   => 'date',
        'fomema_expiry'   => 'date',
        'date_of_join'    => 'date',
        'resign_date'     => 'date',
        'basic_rate'      => 'decimal:2',
    ];

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

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

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

    public function renewals(): HasMany
    {
        return $this->hasMany(Renewal::class)->latest('renewed_on');
    }

    public function renewalsOfType(string $type): HasMany
    {
        return $this->hasMany(Renewal::class)->where('type', $type)
            ->orderByDesc('renewed_on')->orderByDesc('id');
    }

    public function siteAssignments(): HasMany
    {
        return $this->hasMany(SiteAssignment::class)->orderByDesc('assigned_on')->orderByDesc('id');
    }

    public function photoUrl(): ?string
    {
        return $this->photo_path ? route('staff.photo', $this) : null;
    }

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

    public function payslips(): HasMany
    {
        return $this->hasMany(Payslip::class)->orderByDesc('period_year')->orderByDesc('period_month');
    }

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

    // Days until a given expiry (negative = expired). Null if no date.
    public function daysTo(?string $field): ?int
    {
        $date = $this->{$field};
        return $date ? (int) now()->startOfDay()->diffInDays($date->startOfDay(), false) : null;
    }

    public function statusColor(): string
    {
        return match ($this->status) {
            'active' => 'success',
            'resign' => 'secondary',
            default  => 'warning',
        };
    }
}
