<?php

namespace Eminiarts\Aura\Models\Scopes;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;

class TeamScope implements Scope
{
    /**
     * Apply the scope to a given Eloquent query builder.
     *
     * @return void
     */
    public function apply(Builder $builder, Model $model)
    {
        if (config('aura.teams') === false) {
            return $builder;
        }

        // If the Model is a Team Resource, don't apply the scope
        if ($model instanceof \Eminiarts\Aura\Resources\Team) {
            return $builder->whereId(auth()->user()->current_team_id);
        }

        if (auth()->user() && $model instanceof \Eminiarts\Aura\Resources\Role) {
            return $builder->where('posts.team_id', auth()->user()->current_team_id);
        }
        
        if (auth()->user() && $model->getTable() == 'posts') {
            return $builder->where('posts.team_id', auth()->user()->current_team_id);
        }

        if (auth()->user()) {
            return $builder->where('team_id', auth()->user()->current_team_id);
        }

        // Check access?

        return $builder;
    }
}
