<?php

namespace Modules\ClinicCore\Entities;

use Illuminate\Database\Eloquent\Model;

/**
 * Item 1.4 - a single doctor-recorded answer on an appointment.
 *
 * Unique on (appointment_id, template_item_id, side) so re-saving the same
 * item replaces the value rather than appending duplicates. Severity +
 * is_critical are computed at save-time from
 * ClcExamTemplateItem::scoreValue() so the critical-check report (item 4.1)
 * can do a flat WHERE is_critical = 1 without re-evaluating logic.
 */
class ClcAppointmentExamFinding extends Model
{
    protected $table = 'clc_appointment_exam_findings';
    protected $guarded = ['id'];

    protected $casts = [
        'values_json'   => 'array',
        'numeric_value' => 'decimal:3',
        'severity'      => 'integer',
        'is_critical'   => 'boolean',
    ];

    public function appointment() { return $this->belongsTo(ClcAppointment::class, 'appointment_id'); }
    public function template()    { return $this->belongsTo(ClcExamTemplate::class, 'template_id'); }
    public function templateItem(){ return $this->belongsTo(ClcExamTemplateItem::class, 'template_item_id'); }
    public function recorder()    { return $this->belongsTo(\App\User::class, 'recorded_by'); }

    public function scopeCritical($q) { return $q->where('is_critical', true); }
    public function scopeForAppointment($q, $apptId) { return $q->where('appointment_id', $apptId); }
}
