<?php

namespace Modules\VetClinic\Entities;

use Illuminate\Database\Eloquent\Model;

class VcImagingRequest extends Model
{
    protected $table = 'vc_imaging_requests';
    protected $guarded = ['id'];

    protected $casts = [
        'requested_at' => 'datetime',
        'completed_at' => 'datetime',
        'reported_at'  => 'datetime',
    ];

    public function pet()         { return $this->belongsTo(VcPet::class, 'pet_id'); }
    public function owner()       { return $this->belongsTo(\App\Contact::class, 'contact_id'); }
    public function appointment() { return $this->belongsTo(VcAppointment::class, 'appointment_id'); }
    public function modality()    { return $this->belongsTo(VcImagingModality::class, 'modality_id'); }
    public function studies()     { return $this->hasMany(VcImagingStudy::class, 'imaging_request_id')->orderByDesc('uploaded_at'); }

    /** Allocate next reference: IM-{biz}-{0000001}. */
    public static function nextRefNo(int $businessId): string
    {
        return \DB::transaction(function () use ($businessId) {
            $last = static::where('business_id', $businessId)
                ->lockForUpdate()->orderByDesc('id')->value('ref_no');
            $n = 1;
            if ($last && preg_match('/-(\d+)$/', $last, $m)) {
                $n = ((int) $m[1]) + 1;
            }
            return 'IM-' . $businessId . '-' . str_pad((string) $n, 7, '0', STR_PAD_LEFT);
        });
    }
}
