<?php

namespace App\Nova\Filters;

use App\Models\System\Roles\Role;
use Laravel\Nova\Filters\Filter;
use Laravel\Nova\Http\Requests\NovaRequest;

class UserRoleFilter extends Filter
{
    /**
     * The filter's component.
     *
     * @var string
     */
    public $component = 'select-filter';

    /**
     * Get the displayable name of the filter.
     */
    public function name(): string
    {
        return __('Role');
    }

    /**
     * Apply the filter to the given query.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @param  mixed  $value
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function apply(NovaRequest $request, $query, $value)
    {
        return $value
                ? $query->join('model_has_roles', 'id', '=', 'model_id')->where('role_id', $value)
                : $query;
    }

    /**
     * Get the filter's available options.
     *
     * @return array
     */
    public function options(NovaRequest $request)
    {
        return Role::pluck('name', 'id')->map(fn ($data) => __($data))->flip();
    }
}
