<?php

namespace App\Models\api\v1;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class MemberShip extends Model
{
    use HasFactory;

    /**
     * The table associated with the model.
     * 
     * @var string
     */
    protected $table = 'memberships';

    /**
     * The "type" of the auto-incrementing ID.
     * 
     * @var string
     */
    protected $keyType = 'integer';

    /**
     * @var array
     */
    protected $fillable = ['name', 'spaces_memberships_id', 'is_active', 'type', 'spaces_id', 'created_by', 'updated_by', 'updated_at', 'is_deleted', 'deleted_at', 'deleted_by'];
    protected $hidden = ['created_at', 'created_by', 'updated_by', 'updated_at', 'is_deleted', 'deleted_at', 'deleted_by'];



    public static function getMemberShips(int $user_id): array
    {
        $roles         = Role::Where([['is_assignable', 1], ['is_deleted', 0]])->get()->pluck('id')->toArray();
        $user_roles = UserRole::whereIn('role_id', $roles)->Where([['user_id', $user_id], ['is_deleted', 0]])->get()->pluck('id')->toArray();
        $spaces     = UsersRolesSpace::whereIn('user_role_id', $user_roles)->where('is_active', 1)->pluck('space_id')->toArray();
        $memberships = MemberShip::whereIn('spaces_memberships_id', $spaces)->get()->toArray();
        $memberSpaces = array();
        foreach ($memberships as $mem) {
            $space = Space::where('id', $mem['spaces_id'])->first();
            $memberSpaces[] =  $space;
        }
        return $memberSpaces;
    }

    public function space()
    {
        return $this->belongsTo(Space::class);
    }
}
