<?php

namespace Modules\ClinicCore\Entities;

use Illuminate\Database\Eloquent\Model;

class ClcConfidentialNote extends Model
{
    protected $table = 'clc_confidential_notes';
    protected $guarded = ['id'];

    public function creator()
    {
        return $this->belongsTo(\App\User::class, 'created_by');
    }

    public function editor()
    {
        return $this->belongsTo(\App\User::class, 'updated_by');
    }

    public function getIsConfidentialAttribute(): bool
    {
        return $this->visibility === 'confidential';
    }

    /**
     * Filter a query to only the notes the given user is allowed to see for
     * a given (subject_type, subject_id). Confidential notes drop out unless
     * the user has the clinic.view_confidential_notes permission OR is
     * the original author.
     */
    public function scopeVisibleTo($query, $user)
    {
        if ($user && $user->can('clinic.view_confidential_notes')) {
            return $query;
        }
        $authorId = optional($user)->id ?? 0;
        return $query->where(function ($q) use ($authorId) {
            $q->where('visibility', 'normal')
              ->orWhere(function ($qq) use ($authorId) {
                  $qq->where('visibility', 'confidential')
                     ->where('created_by', $authorId);
              });
        });
    }
}
