<?php

namespace Modules\ClinicCore\Entities;

use Illuminate\Database\Eloquent\Model;
use App\User;

/**
 * SIFA P3-T4 — a single trend-capable vitals reading.
 *
 * bmi and gcs_total are auto-derived from the raw inputs on every save (a
 * `saving` model event), so callers never have to compute them and the columns
 * always stay consistent with weight/height and the three GCS components.
 */
class ClcVital extends Model
{
    protected $table = 'clc_vitals';
    protected $guarded = ['id'];

    protected $casts = [
        'recorded_at'   => 'datetime',
        'temperature'   => 'float',
        'spo2'          => 'float',
        'weight_kg'     => 'float',
        'height_cm'     => 'float',
        'bmi'           => 'float',
        'blood_glucose' => 'float',
    ];

    public const GLUCOSE_TIMINGS = ['fasting', 'random', 'post_prandial'];

    protected static function boot()
    {
        parent::boot();

        static::saving(function (ClcVital $vital) {
            $vital->bmi       = $vital->computeBmi();
            $vital->gcs_total = $vital->computeGcsTotal();
        });
    }

    /** BMI = weight(kg) / height(m)^2, rounded to 1 dp. Null if inputs missing. */
    public function computeBmi(): ?float
    {
        $w = (float) $this->weight_kg;
        $h = (float) $this->height_cm;
        if ($w <= 0 || $h <= 0) {
            return null;
        }
        $m = $h / 100;
        return round($w / ($m * $m), 1);
    }

    /** GCS total = eye + verbal + motor, only when all three are present. */
    public function computeGcsTotal(): ?int
    {
        if ($this->gcs_eye === null || $this->gcs_verbal === null || $this->gcs_motor === null) {
            return null;
        }
        return (int) $this->gcs_eye + (int) $this->gcs_verbal + (int) $this->gcs_motor;
    }

    public function patient()
    {
        return $this->belongsTo(ClcPatient::class, 'patient_id');
    }

    public function appointment()
    {
        return $this->belongsTo(ClcAppointment::class, 'appointment_id');
    }

    public function recorder()
    {
        return $this->belongsTo(User::class, 'recorded_by');
    }

    public function scopeForBusiness($query, $businessId)
    {
        return $query->where('business_id', $businessId);
    }
}
