<?php

namespace Modules\NX600Lab\Entities;

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

class NxWorklist extends Model
{
    use SoftDeletes;

    protected $table = 'nx_worklist';

    protected $fillable = [
        'business_id', 'sample_no', 'patient_id', 'patient_name', 'species',
        'sex', 'age', 'test_names', 'is_sent', 'sent_at',
        'contact_id', 'vc_pet_id', 'created_by',
    ];

    protected $casts = [
        'test_names' => 'array',
        'is_sent'    => 'boolean',
        'sent_at'    => 'datetime',
        'sex'        => 'integer',
        'age'        => 'integer',
        'species'    => 'integer',
    ];

    /**
     * The VetClinic pet this order was raised for (synced mode only).
     */
    public function pet()
    {
        return $this->belongsTo(\Modules\VetClinic\Entities\VcPet::class, 'vc_pet_id');
    }

    public function getSpeciesNameAttribute(): string
    {
        $map = NxModuleSetting::speciesMap($this->business_id);
        return $map[$this->species] ?? "Species #{$this->species}";
    }

    public function getSexLabelAttribute(): string
    {
        return match ($this->sex) {
            0 => 'Male',
            1 => 'Female',
            default => 'Unknown',
        };
    }

    public function getStatusLabelAttribute(): string
    {
        return $this->is_sent ? 'Retrieved by device' : 'Pending';
    }

    /**
     * Generate the next unused sample number (prefix L + yymmdd + sequence).
     */
    public static function nextSampleNo(): string
    {
        $prefix = 'L' . now()->format('ymd');
        $seq = static::withTrashed()->where('sample_no', 'like', $prefix . '%')->count() + 1;

        do {
            $candidate = $prefix . str_pad((string) $seq, 3, '0', STR_PAD_LEFT);
            $seq++;
        } while (static::withTrashed()->where('sample_no', $candidate)->exists());

        return $candidate;
    }
}
