<?php

namespace Modules\VetAdmission\Entities;

use Illuminate\Database\Eloquent\Model;
use App\Contact;
use Carbon\Carbon;
use Modules\VetClinic\Entities\VcPet;
use Modules\VetClinic\Entities\VcDoctor;
use Modules\VetClinic\Entities\VcAppointment;

class VaAdmission extends Model
{
    protected $table = 'va_admissions';
    protected $guarded = ['id'];

    protected $casts = [
        'admitted_at'           => 'datetime',
        'expected_discharge_at' => 'datetime',
        'discharged_at'         => 'datetime',
    ];

    public function ward()
    {
        return $this->belongsTo(VaWard::class, 'ward_id');
    }

    public function pet()
    {
        return $this->belongsTo(VcPet::class, 'pet_id');
    }

    public function owner()
    {
        return $this->belongsTo(Contact::class, 'contact_id');
    }

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

    public function admittingDoctor()
    {
        return $this->belongsTo(VcDoctor::class, 'admitting_doctor_id');
    }

    public function attendingDoctor()
    {
        return $this->belongsTo(VcDoctor::class, 'attending_doctor_id');
    }

    public function carePlan()
    {
        return $this->hasMany(VaAdmissionCarePlan::class, 'admission_id');
    }

    public function careLogs()
    {
        return $this->hasMany(VaCareLog::class, 'admission_id');
    }

    public function vitals()
    {
        return $this->hasMany(VaAdmissionVital::class, 'admission_id')->orderByDesc('recorded_at');
    }

    public function getIsActiveAttribute()
    {
        return $this->status === 'admitted';
    }

    /** Length of stay in days (so far, or until discharge). */
    public function getStayDaysAttribute()
    {
        $start = $this->admitted_at ? Carbon::parse($this->admitted_at) : null;
        if (!$start) return 0;
        $end = $this->discharged_at ? Carbon::parse($this->discharged_at) : Carbon::now();
        return max(1, $start->diffInDays($end) + 1);
    }

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

    public function scopeAdmitted($query)
    {
        return $query->where('status', 'admitted');
    }
}
