<?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 ViewPermissionScope implements Scope
{
    public function apply(Builder $builder, Model $model)
    {
        $user = Auth::user();
        if (! $user) {
            $builder->whereRaw('1 = 0');
        } elseif (! $user->can('view_all_performance::card')) {
            // For models with assignees relation (like PerformanceCard), include assigned users
            if (method_exists($model, 'assignees')) {
                $builder->where(function ($q) use ($user, $model) {
                    $q->where($model->getTable().'.created_by', $user->id)
                        ->orWhereHas('assignees', function ($q2) use ($user) {
                            $q2->where('users.id', $user->id);
                        });
                });
            } else {
                $builder->where($model->getTable().'.created_by', $user->id);
            }
        }
    }
}
