<?php

namespace Modules\MedWard\Entities;

use Illuminate\Database\Eloquent\Model;

/**
 * An ICU flow-sheet row (SIFA P6-T5 icu_flow_sheet). map_calc is populated by
 * IcuService on save; crossing the configured MAP / SpO2 floors raises an
 * idempotent MedicalAlertService critical_value alert per row.
 */
class MedwardIcuFlowsheet extends Model
{
    protected $table = 'medward_icu_flowsheets';

    protected $guarded = ['id'];

    protected $casts = [
        'recorded_at'  => 'datetime',
        'map_calc'     => 'float',
        'spo2'         => 'float',
        'temp'         => 'float',
        'fio2'         => 'float',
        'peep'         => 'float',
        'tidal_volume' => 'float',
        'vasoactives'  => 'array',
        'drains'       => 'array',
    ];

    public function admission()
    {
        return $this->belongsTo(MedwardAdmission::class, 'admission_id');
    }

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

    /**
     * Mean arterial pressure from systolic + diastolic: (sys + 2*dia)/3. Null
     * when either component is missing.
     */
    public static function computeMap($sys, $dia): ?float
    {
        if ($sys === null || $sys === '' || $dia === null || $dia === '') {
            return null;
        }

        return round(((float) $sys + 2 * (float) $dia) / 3, 2);
    }
}
