<?php

namespace Modules\MedWard\Entities;

use Illuminate\Database\Eloquent\Model;

/**
 * A per-shift fluid intake / output row (SIFA P6-T2 fluid_balance). The net
 * balance is COMPUTED here (accessor) rather than stored, so a corrected line is
 * always consistent.
 */
class MedwardFluidBalance extends Model
{
    protected $table = 'medward_fluid_balance';

    protected $guarded = ['id'];

    protected $casts = [
        'recorded_at'  => 'datetime',
        'intake_oral'  => 'float',
        'intake_iv'    => 'float',
        'intake_other' => 'float',
        'output_urine' => 'float',
        'output_drain' => 'float',
        'output_other' => 'float',
    ];

    protected $appends = ['intake_total', 'output_total', 'balance'];

    public const SHIFTS = ['morning', 'evening', 'night'];

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

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

    public function getIntakeTotalAttribute(): float
    {
        return round((float) $this->intake_oral + (float) $this->intake_iv + (float) $this->intake_other, 2);
    }

    public function getOutputTotalAttribute(): float
    {
        return round((float) $this->output_urine + (float) $this->output_drain + (float) $this->output_other, 2);
    }

    /** Net fluid balance (ml): total intake − total output. */
    public function getBalanceAttribute(): float
    {
        return round($this->intake_total - $this->output_total, 2);
    }
}
