<?php

namespace App\Models;

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

class Organization extends Model
{
    use HasFactory;

    protected $fillable = [
        'code',
        'name',
        'type',
        'status',
        'description',
        'part_of',
        'main_address_id',
        'corporate_id_partner',
    ];

    // public $with = [
    //     'metas'
    // ];

    public $appends = [
        'meta'
    ];

    protected $hidden = [
        'created_at',
        'updated_at',
        'deleted_at',
        'created_by',
        'updated_by',
        'deleted_by',
    ];

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

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

    public function setCodeAttribute($value)
    {
        $this->attributes['code'] = !empty($value) ? $value : Str::upper(Str::random('6'));
    }

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

        return (object) $orgMeta;
    }

    public function addresses()
    {
        return $this->morphMany(Address::class, 'addressable');
    }

    public function currentAddress()
    {
        return $this->belongsTo(Address::class, 'main_address_id');
    }

    public function parent()
    {
        return $this->belongsTo(Organization::class, 'part_of', 'id');
    }

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

    public function practitionerRoles()
    {
        return $this->hasMany(PractitionerRole::class, 'organization_id');
    }

    public function claims()
    {
        return $this->hasMany(Claim::class, 'organization_id', 'id');
    }
    public function claim_request()
    {
        return $this->hasMany(ClaimRequest::class, 'organization_id', 'id');
    }
    public function claim_history_care()
    {
        return $this->hasOne(ClaimHistoryCare::class, 'organization_id', 'id');
    }
}
