@php
    $id = $id ?? ( 'tag_id_' . rand(1000, 9999) );
    $name = $name ?? $id;
    $showSystemMessageOnCreate = $showSystemMessageOnCreate ?? false;
    $enableCreate = $enableCreate ?? true;
    $datatables = $datatables ?? null;
    
    // if exist collection of 'the most used tags' display after select
    $mostUsedTags = $mostUsedTags ?? [];
    $mostUsedTags = App\Http\Resources\Select2\Tag::collection($mostUsedTags);
    
    
    // if exist 'entity' select his tags
    if(isset($entity)){
        $value = $entity->tags->pluck('id')->toArray();
    } else {
        $value = [];
    }
    
    $tagsId = old($name, $value);
    $tags = App\Models\Tag::whereIn('id', $tagsId)->get();
    $tags = App\Http\Resources\Select2\Tag::collection($tags);
    
@endphp

<div class="mb-2">
    <select class="select2 form-control select2-hidden-accessible"
            multiple="multiple"
            data-placeholder="@lang('-- Izaberi tag --')"
            name="{{$name}}[]"
            id="{{$id}}"
    >
    </select>
</div>
@if(isset($mostUsedTags) && count($mostUsedTags) > 0)
<label class="control-label">@lang('Najviše korišteni tagovi')</label>
    <div class="d-flex flex-wrap">
        @foreach($mostUsedTags as $tag)
            <div 
                class="btn btn-sm btn-secondary waves-effect waves-light empty-form most-used-tags mr-1 mb-1"
                data-id="{{$tag->id}}"
            >
                        {{$tag->title}}
            </div>
        @endforeach
    </div>
@endif

@push('footer_scripts')
<script>
    let value = {!!json_encode($tags)!!};
    let mostUsedTags = {!!json_encode($mostUsedTags)!!};
    
    $('[name="{{$name}}[]"]').tagsSelect({
        sourceUrl: '{{$tagSelectUrl}}',
        storeUrl: '{{$tagStoreUrl}}',
        showSystemMessageOnCreate: '{{$showSystemMessageOnCreate}}',
        enableCreate: '{{$enableCreate}}',
        newTagLabel: " (@lang('Dodaj novi tag'))",
        datatables: '{{$datatables}}',
        value: value,
        mostUsedTags: mostUsedTags
    });
</script>
@endpush