<?php

namespace App\Repositories\Eloquent\Criteria;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\DB;
use Prettus\Repository\Contracts\CriteriaInterface;
use Prettus\Repository\Contracts\RepositoryInterface;

/**
 * Class AnyRolePouzivatelaCriteria
 *
 * @package App\Repositories\Eloquent\Criteria
 */
final class AnyRolePouzivatelaCriteria implements CriteriaInterface
{
    /**
     * @param Builder $model
     * @param RepositoryInterface $repository
     *
     * @return Builder
     */
    public function apply($model, RepositoryInterface $repository): Builder
    {
        $userRoles = auth()->user()->getRoleNames()->toArray();
        $dbArray = DB::raw('ARRAY[\'' . implode('\',\'', $userRoles) . '\']');

        return $model->whereRaw(sprintf('zverejnit_pre_pouzivatelov_podla_role::jsonb ??| %s', $dbArray));
    }
}
