<?php

namespace Modules\MedDocuments\Entities;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * Document header. Generic polymorphic attach (entity_type / entity_id) lets
 * any module bind a document to any record; contact_id is the optional patient
 * link. current_version_id points at the latest MeddocVersion.
 */
class MeddocDocument extends Model
{
    use SoftDeletes;

    protected $table = 'meddoc_documents';

    protected $guarded = ['id'];

    protected $casts = [
        'tags'               => 'array',
        'current_version_id' => 'integer',
    ];

    public function type()
    {
        return $this->belongsTo(MeddocType::class, 'doc_type_id');
    }

    public function versions()
    {
        return $this->hasMany(MeddocVersion::class, 'document_id')->orderByDesc('version_no');
    }

    public function currentVersion()
    {
        return $this->belongsTo(MeddocVersion::class, 'current_version_id');
    }

    public function shares()
    {
        return $this->hasMany(MeddocShare::class, 'document_id');
    }

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

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