<?php

namespace App\Models;

use App\Models\Concerns\BelongsToOwner;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class MarOrder extends Model
{
    use BelongsToOwner, SoftDeletes;

    public const STATUS_ACTIVE = 'active';

    public const STATUS_PAUSED = 'paused';

    public const STATUS_STOPPED = 'stopped';

    protected $table = 'care_mar_orders';

    protected $fillable = [
        'owner_ref',
        'organization_id',
        'visit_id',
        'patient_id',
        'prescription_id',
        'prescription_item_id',
        'drug_name',
        'dosage',
        'route',
        'frequency_code',
        'times_of_day',
        'is_prn',
        'status',
        'starts_at',
        'ends_at',
        'instructions',
    ];

    protected function casts(): array
    {
        return [
            'times_of_day' => 'array',
            'is_prn' => 'boolean',
            'starts_at' => 'datetime',
            'ends_at' => 'datetime',
        ];
    }

    public function visit(): BelongsTo
    {
        return $this->belongsTo(Visit::class, 'visit_id');
    }

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

    public function prescription(): BelongsTo
    {
        return $this->belongsTo(Prescription::class, 'prescription_id');
    }

    public function prescriptionItem(): BelongsTo
    {
        return $this->belongsTo(PrescriptionItem::class, 'prescription_item_id');
    }

    public function administrations(): HasMany
    {
        return $this->hasMany(MarAdministration::class, 'mar_order_id')->orderByDesc('recorded_at');
    }
}
