<?php

namespace App\Models;

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

class PractitionerRole extends Model
{
    use HasFactory;

    protected $fillable = [
        'practitioner_id',
        'organization_id',
        'speciality_id',
        'identifier_id',
        'period_start',
        'period_end',
        'active',
    ];

    public $appends = [
        'meta'
    ];

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

        return (object) $orgMeta;
    }


    /**
     * Scope a query to only include active data.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @return void
     */
    public function scopeActive($query)
    {
        $query->where('active', 1);
    }

    public function getIsChatAvailableAttribute()
    {
        return $this->practices->where('service_code', 'chat')->where('active', 1)->count() >= 1;
    }

    public function getIsWalkinAvailableAttribute()
    {
        return $this->practices->where('service_code', 'walkin')->where('active', 1)->count() >= 1;
    }

    public function getIsVideoAvailableAttribute()
    {
        return $this->practices->where('service_code', 'video')->where('active', 1)->count() >= 1;
    }

    public function getIsInstantChatAvailableAttribute()
    {
        return $this->practices->where('service_code', 'instant-chat')->where('active', 1)->count() >= 1;
    }

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

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

    public function practitioner()
    {
        return $this->belongsTo(Practitioner::class, 'practitioner_id');
    }

    public function speciality()
    {
        return $this->belongsTo(Speciality::class, 'speciality_id');
    }

    public function practices()
    {
        return $this->hasMany(Practice::class, 'practitioner_role_id');
    }

    public function prices()
    {
        return $this->hasManyThrough(Price::class, Practice::class, 'practitioner_role_id', 'id');
    }

    public function availabilities()
    {
        return $this->hasMany(PractitionerRoleAvailability::class, 'practitioner_role_id');
    }

    public function person()
    {
        return $this->hasOneThrough(Person::class, Practitioner::class, 'person_id', 'id');
    }

    public function appointmentParticipantables()
    {
        return $this->morphMany(AppointmentParticipant::class, 'participantable');
    }
}
