<?php

namespace App\Models\Advisories;

use App\Models\Companies\Company;
use App\Support\RelationValuesTrait;
use App\Support\UuidScopeTrait;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class AdvisoryCompany extends Model {
    use UuidScopeTrait, RelationValuesTrait;

    protected $dates = [
    ];

    protected $fillable = [
        'uuid',
        'advisory_id',
        'company_id'
    ];

    protected $hidden = [
        'id'
    ];



    public function advisory(): BelongsTo {
        return $this->belongsTo(Advisory::class);
    }

    public function company(): BelongsTo {
        return $this->belongsTo(Company::class);
    }

    public function advisoryMembers() {
        return $this->advisory->members()->whereHas('companyMember', function($query) {
            $query->where(['company_id' => $this->company_id]);
        });
    }

    public function companyMembers(): BelongsToMany {
        return $this->advisory->companyMembers()->where(['company_id' => $this->company_id]);
    }



    public function getTitleAttribute(): string {
        return "Член {$this->advisory->number} {$this->company->name}";
    }

    public function getSubtitleAttribute(): string {
        return "Член {$this->advisory->number}";
    }

    public function getVoterAttribute(): ?Model {
        return $this->advisoryMembers()->where(['rank' => AdvisoryMemberRank::VOTER])->first();
    }


    public function getCompanyMembers($rank): BelongsToMany {
        return $this->companyMembers()->wherePivot('rank', '=', $rank);
    }


}
