<?php

namespace App\Filters;

use App\Models\Tenancy\Position;
use App\Models\Tenancy\Procedure;
use Illuminate\Database\Eloquent\Builder;
use Spatie\QueryBuilder\Filters\Filter;

class FiltersEmployeeProcedures implements Filter
{
    public function __invoke(Builder $query, $value, string $property)
    {
        $servicesFromProcedures = Procedure::whereIn('id', (array) $value)
            ->pluck('services_id')
            ->unique()
            ->toArray();
        $positionsFromServices = Position::whereIn('services_id', $servicesFromProcedures)
            ->pluck('id')
            ->toArray();
        $query->where(function ($q) use ($positionsFromServices) {
            foreach ($positionsFromServices as $position) {
                $q->orWhereRaw("FIND_IN_SET(?, position_id) > 0", [$position]);
            }
        });
    }
}
