<?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 DonorPortfolioAccessScope implements Scope
{
    /**
     * Apply the scope to a given Eloquent query builder.
     */
    public function apply(Builder $builder, Model $model): void
    {
        if (! Auth::check()) {
            return;
        }

        $user = Auth::user();

        // users with permission to view all portfolios can see everything
        if ($user->can('view_all_portfolios_donor::financial::portfolio')) {
            return;
        }

        // Regular users can only see portfolios they have access to through the relationship
        $builder->whereHas('users', function ($query) use ($user) {
            $query->where('users.id', $user->id);
        });
    }
}
