<?php

namespace Modules\VetClinic\Entities;

use Illuminate\Database\Eloquent\Model;

/**
 * Item 1.4 - a named exam (General Exam, Orthopedic, Neuro, ...) made up
 * of many VcExamTemplateItem rows grouped into regions.
 *
 * business_id NULL = system-shipped template available to every clinic.
 * Per-business templates shadow same-name system ones at lookup time.
 */
class VcExamTemplate extends Model
{
    protected $table = 'vc_exam_templates';
    protected $guarded = ['id'];

    protected $casts = [
        'is_active'  => 'boolean',
        'sort_order' => 'integer',
    ];

    public function items()
    {
        return $this->hasMany(VcExamTemplateItem::class, 'template_id')
            ->orderBy('region')->orderBy('sort_order');
    }

    public function scopeActive($q)         { return $q->where('is_active', true); }
    public function scopeGeneral($q)        { return $q->where('kind', 'general'); }
    public function scopeSpecialist($q)     { return $q->where('kind', 'specialist'); }
    public function scopeForBusiness($q, $businessId)
    {
        return $q->where(function ($qq) use ($businessId) {
            $qq->whereNull('business_id')->orWhere('business_id', $businessId);
        });
    }
    public function scopeForSpecies($q, $species)
    {
        $species = $species ?: 'all';
        return $q->where(function ($qq) use ($species) {
            $qq->where('species_scope', 'all')->orWhere('species_scope', $species);
        });
    }
}
