<?php

namespace App\Repositories;

use App\Repositories\QueryBuilder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;
use Spatie\MediaLibrary\MediaCollections\Models\Media;

class Member extends Model implements HasMedia, QueryBuilder\ConfigProvider
{

	use SoftDeletes, InteractsWithMedia;

	protected $dates = ['deleted_at'];

	protected $guarded = ['id'];

	public function getSlugAttribute()
	{
		return $this->id . '-' . Str::slug($this->formal_name);
	}

	public function summaries()
	{
		return $this->hasMany(Summary::class);
	}

	public function contributions()
	{
		return $this->hasMany(Contribution::class);
	}

	public function addresses()
	{
		return $this->hasMany(Address::class);
	}

	public function contacts()
	{
		return $this->hasMany(Contact::class);
	}

	public function management_links()
	{
		return $this->hasMany(ManagementLink::class);
	}

	public function main_branch()
	{
		return $this->hasOne(Branch::class, 'id', 'branch_id');
	}

	public function revision()
	{
		return $this->hasOne(Revision::class);
	}

	public function sub_branches()
	{
		return $this->belongsToMany(Branch::class, 'branch_members')->using(BranchMember::class);
	}

    public function users()
    {
        return $this->belongsToMany(User::class, 'member_users');
    }

	public function registerMediaCollections(): void
	{
		$this
			->addMediaCollection('members_logos')
			->singleFile();
	}

	public function registerMediaConversions(Media $media = null): void
	{
		$this->addMediaConversion('thumb')
			->height(50);
	}

    public static function getQueryBuilderConfig(): QueryBuilder\Config
    {
        return (new QueryBuilder\Config())
            ->setAllowedFilters(['show_on_website'])
            ->setAllowedSorts(['id', 'informal_name']);
    }
}
