<?php

namespace App\Models;

use App\Enums\EmploymentStatus;
use App\Enums\Gender;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;
use Veelasky\LaravelHashId\Eloquent\HashableId;

class Employee extends Model
{
    use HasFactory, HashableId, SoftDeletes;

    protected $guarded = ['id'];

    protected function casts(): array
    {
        return [
            'gender' => Gender::class,
            'status' => EmploymentStatus::class,
        ];
    }

    public static function generateEmployeeCode(): string
    {
        $prefix = 'EMP';
        $year = date('Y');

        $lastEmployee = self::where('code', 'like', "$prefix$year%")
            ->orderBy('code', 'desc')
            ->first();

        if ($lastEmployee) {
            $lastNumber = (int) substr($lastEmployee->code, strlen($prefix) + 4);
            $newNumber = $lastNumber + 1;
        } else {
            $newNumber = 1;
        }

        $numberFormatted = str_pad($newNumber, 4, '0', STR_PAD_LEFT);

        return $prefix.$year.$numberFormatted;
    }

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