use App\Action;
use App\Discussion;
use App\File;
use App\Tag;
use App\User;
use App\Group;
use Auth;
use Illuminate\Http\Request;
class TagController extends Controller
{
    //
    public function show(Request $request, Tag $tag)
    {
        if (Auth::user()->getPreference('show', 'my') == 'admin') {
            // build a list of groups the user has access to
            if (Auth::user()->isAdmin()) { // super admin sees everything
                $groups = Group::get()
                    ->pluck('id');
            }
        }
        if (Auth::user()->getPreference('show', 'my') == 'all') {
            $groups = Group::public()
                ->get()
                ->pluck('id')
                ->merge(Auth::user()->groups()->pluck('groups.id'));
        }
        if (Auth::user()->getPreference('show', 'my') == 'my') {
            $groups = Auth::user()->groups()->pluck('groups.id');
        }
        $discussions = Discussion::whereHas('group', function ($q) use ($groups) {
            $q->whereIn('group_id', $groups);
        })
            ->whereHas('tags', function ($q) use ($tag) {
                $q->where('normalized', $tag->normalized);
            })
            ->get();
        $files = File::whereHas('group', function ($q) use ($groups) {
            $q->whereIn('group_id', $groups);
        })
            ->whereHas('tags', function ($q) use ($tag) {
                $q->where('normalized', $tag->normalized);
            })
            ->get();
        $actions = Action::whereHas('group', function ($q) use ($groups) {
            $q->whereIn('group_id', $groups);
        })
            ->whereHas('tags', function ($q) use ($tag) {
                $q->where('normalized', $tag->normalized);
            })
            ->get();
        $users = User::whereHas('groups', function ($q) use ($groups) {
            $q->whereIn('group_id', $groups);
        })
            ->whereHas('tags', function ($q) use ($tag) {
                $q->where('normalized', $tag->normalized);
            })
            ->get();
        $groups = Group::whereIn('id', $groups)
            ->whereHas('tags', function ($q) use ($tag) {
                $q->where('normalized', $tag->normalized);
            })
            ->get();
        return view('dashboard.tags-show')
            ->with('discussions', $discussions)
            ->with('files', $files)
            ->with('users', $users)
            ->with('actions', $actions)
            ->with('groups', $groups)
            ->with('tag', $tag)
            ->with('title', $tag->name);
 
   }
}