<?php

namespace Modules\MedPortal\Entities;

use Illuminate\Database\Eloquent\Model;

/**
 * A questionnaire definition (SIFA Phase 8). System rows (business_id NULL) ship
 * the standard PHQ-9 and GAD-7 instruments; businesses may add `custom` ones.
 */
class MportalQuestionnaire extends Model
{
    protected $table = 'mportal_questionnaires';

    protected $guarded = ['id'];

    protected $casts = [
        'items'     => 'array',
        'scoring'   => 'array',
        'is_active' => 'boolean',
    ];

    public const CODES = ['phq9', 'gad7', 'custom'];

    public function responses()
    {
        return $this->hasMany(MportalQuestionnaireResponse::class, 'questionnaire_id');
    }

    /** System (business_id NULL) + this business's own questionnaires. */
    public function scopeAvailableTo($query, $businessId)
    {
        return $query->where(function ($q) use ($businessId) {
            $q->whereNull('business_id')->orWhere('business_id', $businessId);
        });
    }
}
