<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Relation;

class Encounter extends Model
{
    use HasFactory;

    public $fillable = [
        'part_of',
        'status',
        'class',
        'type',
        'patient_id',
        'healthcare_id',
        'start',
        'end',
        'number_of_bed',
        'duration_day'
    ];

    public $casts = [
        'start' => 'datetime',
        'end' => 'datetime'
    ];

    public static $status_enums = [
        'completed' => 'Completed',
        'planned' => 'Planned',
        'in-progress' => 'In Progress',
        'on-hold' => 'On Hold',
        'discharged' => 'Discharged',
        'completed' => 'Completed',
        'cancelled' => 'Cancelled',
        'discontinued' => 'Discontinued',
        'entered-in-error' => 'Entered in Error',
        'unknown' => 'Unknown',
    ];

    public $with = [
        'metas'
    ];
    
    public $append = [
        'meta'
    ];

    public function participants()
    {
        return $this->hasMany(EncounterParticipant::class, 'encounter_id');
    }

    public function claim()
    {
        return $this->belongsTo(Claim::class);
    }


    public function doctors()
    {
        
        // return $this->hasManyThrough(CorporateService::class, Service::class, 'corporate_id', 'service_code', 'id', 'service_code');

        return $this->hasManyThrough(Practitioner::class, EncounterParticipant::class, 'encounter_id', 'id', 'id', 'participantable_id')
            ->where(
                'participantable_type', 
                array_search(static::class, Relation::morphMap()) ?: Practitioner::class
            );
    }

    public function diagnoses()
    {
        return $this->hasMany(EncounterDiagnosis::class, 'encounter_id');
    }

    public function healthcare()
    {
        return $this->belongsTo(Organization::class, 'healthcare_id');
    }

    public function metas()
    {
        return $this->morphMany(Meta::class, 'metaable');
    }

    public function primaryDiagnoses()
    {
        return $this->diagnoses()->where('type', 'primary');
    }

    public function secondaryDiagnoses()
    {
        return $this->diagnoses()->wher('type', 'primary');
    }

    public function service()
    {
        return $this->belongsTo(Service::class, 'class', 'code');
    }


    public function getMetaAttribute()
    {
        $orgMeta = [];
        foreach ($this->metas as $meta) {
            $orgMeta[$meta->type] = $meta->value;
        }

        return (object) $orgMeta;
    }
}
