<?php

namespace App\Scopes;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
use Illuminate\Support\Facades\Auth;

class AdminsTaskViewScope implements Scope
{
    public function apply(Builder $builder, Model $model)
    {
        $user = Auth::user();

        if (! $user) {
            $builder->whereRaw('1 = 0');

            return;
        }

        // If user can view all admins tasks, don't apply any restrictions
        if ($user->can('view_all_admins::task')) {
            return;
        }

        // Otherwise, only show tasks that are either:
        // 1. Created by the user
        // 2. Assigned to the user
        $builder->where(function ($query) use ($user, $model) {
            $query->where($model->getTable().'.created_by', $user->id)
                ->orWhereHas('assignedUsers', function ($assignedQuery) use ($user) {
                    $assignedQuery->where('users.id', $user->id);
                });
        });
    }
}
