<?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
 */
final class AnyRolePouzivatelaCriteria implements CriteriaInterface
{
    /**
     * @param  Builder  $model
     */
    public function apply($model, RepositoryInterface $repository): Builder
    {
        $userRoles = auth()->user()->getRoleNames()->toArray();
        $dbArray = DB::raw('ARRAY[\''.implode('\',\'', $userRoles).'\']');

        return $model->where(function ($query) use ($dbArray) {
            $query
                ->whereJsonLength('zverejnit_pre_pouzivatelov_podla_role', 0)
                ->orWhereJsonLength('zverejnit_pre_pouzivatelov_podla_role', null)
                ->orWhereRaw(sprintf('zverejnit_pre_pouzivatelov_podla_role::jsonb ??| %s', $dbArray));
        });
    }
}
