<div class="table-responsive">


    <div class="table-buttons py-2 bg-primary rounded-start d-flex flex-column ">
        <button type="button" class="btn btn-sm text-white" data-bs-toggle="modal"
                data-bs-target="#table_{{ $id }}_modal_search">
            <i class="bi bi-search"></i>
        </button>

        <button type="button" class="btn btn-sm text-white " data-bs-toggle="modal"
                data-bs-target="#table_{{ $id }}_modal_filters">
            <i class="bi bi-funnel-fill"></i>
        </button>

        <button type="button" class="btn btn-sm text-white " data-bs-toggle="modal"
                data-bs-target="#table_{{ $id }}_modal_settings">
            <i class="bi bi-gear-fill"></i>
        </button>
    </div>
    <table class="table" id="tbl" data-table-name="{{ $id }}" style="display: none;">
        <thead>
        <tr>
            @foreach($header as $headerName => $headerTitle)
                <th scope="col" class="bg-primary-subtle column_{{ $headerName }}">
                        <span class="cursor-pointer sort-by-column" data-name="{{ $headerName }}">
                            {{ $headerTitle }}
                            @if(str_starts_with($headerName, $sortBy))
                                @if($orderBy === 'asc')
                                    <i class="bi bi-arrow-up"></i>
                                @else
                                    <i class="bi bi-arrow-down"></i>
                                @endif
                            @endif

                            @if(isset(request()->filters[$headerName]) ||
                                isset(request()->filters[str_replace('_txt', '', $headerName) . '_from']) ||
                                isset(request()->filters[str_replace('_txt', '', $headerName) . '_to'])
                                )
                                <i class="bi bi-funnel"></i>
                            @endif
                        </span>
                </th>
            @endforeach

        </tr>
        </thead>
        <tbody>
        @foreach($strings as $string)
            <tr>
                @foreach($header as $headerName => $headerTitle)
                    <td class="column_{{$headerName}}"
                        @if(isset($routeName) && !str_contains($headerName, 'image')) onclick="location.href='{{ route($routeName, $string->id) }}'" @endif>
                        @if(str_contains($headerName, '-'))
                            @php
                                list($rel, $field) = explode('-', $headerName);
                            @endphp
                            @if(isset($string->$rel->$field))
                                @if(str_ends_with($field, '_id'))
                                @php
                                    $relation = \Illuminate\Support\Str::camel(str_replace('_id', '', $field));
                                @endphp
                                    {!! $string->$rel->$relation?->name; !!}
                                @else
                                    @if(str_contains($field, 'image') && $string->$rel->$field)
                                    <a href="{{ $string->$rel->$field }}" data-toggle="lightbox" data-gallery="photos" data-size="fullscreen">
                                        <img src="{{ $string->$rel->$field }}" alt="" class="img-thumbnail maf-img">
                                    </a>
                                    @else
                                    {!! $string->$rel->$field !!}
                                    @endif
                                @endif
                            @else

                                <ul class="small mb-0 list-group list-group-flush bg-secondary">
                                    @foreach($string->$rel ?? [] as $item)
                                        <li class="list-group-item py-0 bg-body-secondary">
                                            {!! $item->$field !!}
                                        </li>
                                    @endforeach
                                </ul>
                            @endif
                        @elseif(str_ends_with($headerName, '_id'))
                            @php
                                $relation = \Illuminate\Support\Str::camel(str_replace('_id', '', $headerName));
                            @endphp
                            {!! $string->$relation?->name; !!}
                        @elseif(str_ends_with($headerName, '_date') && ($string->$headerName))
                            {{ \App\Helpers\DateHelper::getHumanDate($string->$headerName, true) }}
                        @elseif(str_contains($headerName, 'image') && $string->$headerName)
                            <a href="{{ $string->$headerName }}" data-toggle="lightbox" data-gallery="photos" data-size="fullscreen">
                                <img src="{{ $string->$headerName }}" alt="" class="img-thumbnail maf-img">
                            </a>
                        @else
                            {!! $string->$headerName !!}
                        @endif
                    </td>
                @endforeach
            </tr>
        @endforeach
        </tbody>
    </table>
</div>

<!-- Модальное окно настроек таблицы -->
<div class="modal fade" id="table_{{ $id }}_modal_settings" tabindex="-1" aria-labelledby="exampleModalLabel"
     aria-hidden="true">
    <div class="modal-dialog modal-fullscreen-sm-down">
        <div class="modal-content">
            <div class="modal-header">
                <h1 class="modal-title fs-5" id="exampleModalLabel">Выбор отображаемых колонок</h1>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Закрыть"></button>
            </div>
            <div class="modal-body">
                @foreach($header as $headerName => $headerTitle)
                    <div>
                        <label class="me-3"><input type="checkbox" checked="checked" data-name="{{ $headerName }}"
                                                   class="toggle-column checkbox-{{ $headerName }}"> {{ $headerTitle }}
                        </label>
                    </div>
                @endforeach
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Закрыть</button>
            </div>
        </div>
    </div>
</div>

<!-- Модальное окно фильтров -->
<div class="modal fade" id="table_{{ $id }}_modal_filters" tabindex="-1" aria-labelledby="exampleModalLabel"
     aria-hidden="true">
    <div class="modal-dialog modal-fullscreen-sm-down modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h1 class="modal-title fs-5" id="exampleModalLabel">Фильтры по колонкам таблицы</h1>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Закрыть"></button>
            </div>
            <div class="modal-body">
                <form class="filters">
                    @if(isset($filters) && is_array($filters))
                        @foreach($filters as $filterName => $filter)
                            @php $filter['values'] = ['' => ''] + $filter['values'] @endphp
                            @include('partials.select', [
                                    'name' => 'filters[' . $filterName . ']',
                                    'title' => $filter['title'],
                                    'options' => $filter['values'],
                                    'value' => request()->filters[$filterName] ?? '',
                                ])
                        @endforeach
                    @endif

                    @if(isset($ranges) && is_array($ranges))

                        @foreach($ranges as $rangeName => $range)

                            @include('partials.input', [
                                    'name' => 'filters[' . $rangeName . '_from]',
                                    'type' => 'number',
                                    'title' => $range['title'] . ' с:',
                                    'min' => $range['min'],
                                    'max' => $range['max'],
                                    'value' => request()->filters[$rangeName . '_from'] ?? '', // $range['min']
                                ])
                            @include('partials.input', [
                                    'name' => 'filters[' . $rangeName . '_to]',
                                    'type' => 'number',
                                    'title' => ' по:',
                                    'min' => $range['min'],
                                    'max' => $range['max'],
                                    'value' => request()->filters[$rangeName . '_to'] ?? '', // $range['max']
                                ])
                        @endforeach
                    @endif
                    @if(isset($dates) && is_array($dates))

                        @foreach($dates as $rangeName => $range)
                            @include('partials.input', [
                                    'name' => 'filters[' . $rangeName . '_from]',
                                    'type' => 'date',
                                    'title' => $range['title'] . ' с:',
                                    'min' => $range['min'],
                                    'max' => $range['max'],
                                    'value' => request()->filters[$rangeName . '_from'] ?? '',
                                ])
                            @include('partials.input', [
                                    'name' => 'filters[' . $rangeName . '_to]',
                                    'type' => 'date',
                                    'title' => $range['title'] . ' по:',
                                    'min' => $range['min'],
                                    'max' => $range['max'],
                                    'value' => request()->filters[$rangeName . '_to'] ?? '',
                                ])
                        @endforeach
                    @endif
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary accept-filters" data-bs-dismiss="modal">Применить</button>
                <button type="button" class="btn btn-outline-secondary reset-filters" data-bs-dismiss="modal">Сбросить
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Модальное окно поиска -->
<div class="modal fade" id="table_{{ $id }}_modal_search" tabindex="-1" aria-labelledby="exampleModalLabel"
     aria-hidden="true">
    <div class="modal-dialog modal-fullscreen-sm-down modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h1 class="modal-title fs-5" id="exampleModalLabel">Поиск</h1>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Закрыть"></button>
            </div>
            <div class="modal-body">
                <div>
                    Поиск ведётся по следующим колонкам:
                    <span class="fst-italic">
                        @foreach($searchFields as $searchField)
                            {{ $header[$searchField] }}
                            @if(!$loop->last)
                                ,
                            @endif
                        @endforeach
                    </span>
                </div>
                <form class="search-form">
                    @include('partials.input', [
                        'name'  => 's',
                        'title' => 'Поиск',
                        'placeholder' => 'что ищем?',
                        'value' => request()->s ?? '',
                    ])
                </form>

            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary accept-search" data-bs-dismiss="modal">Найти</button>
                <button type="button" class="btn btn-outline-secondary reset-search" data-bs-dismiss="modal">Сбросить
                </button>
            </div>
        </div>
    </div>
</div>

@push('scripts')
    <script type="module">
        // on page load set column visible
        let tbl = $('#tbl');
        let tableName = tbl.attr('data-table-name');
        let tables = JSON.parse(localStorage.getItem('table_' + tableName));

        // on first load create tables object
        if (!tables) {
            tables = {};
        }

        // hide disabled columns
        $.each(tables, function (colName, colStatus) {
            if (!colStatus) {
                $('.checkbox-' + colName).attr('checked', false);
                $('.column_' + colName).hide();
            }
        });

        // highlight search text
        let searchText = $('.search-form input').val();
        if (searchText !== '') {
            let innerHTML = tbl.html();
            let index = innerHTML.indexOf(searchText);
            if (index >= 0) {
                innerHTML = innerHTML.substring(0, index) + "<span class='highlight'>" + innerHTML.substring(index, index + searchText.length) + "</span>" + innerHTML.substring(index + searchText.length);
                tbl.html(innerHTML);
            }
        }

        $('.table').fadeIn();

        $('.toggle-column').on('change', function () {
            let columnName = $(this).attr('data-name');
            let columnStatus = $(this).is(':checked');

            // save column status
            tables[columnName] = columnStatus;
            localStorage.setItem('table_' + tableName, JSON.stringify(tables));

            // show or hide column
            if (columnStatus) {
                $('.column_' + columnName).show('fast');
            } else {
                $('.column_' + columnName).hide('fast');
            }
        });

        $('.sort-by-column').on('click', function () {
            let columnName = $(this).attr('data-name');
            let currentUrl = new URL(document.location.href);
            let currentColumnName = currentUrl.searchParams.get('sortBy');
            currentUrl.searchParams.set('sortBy', columnName);
            if ((currentColumnName !== columnName) || (currentUrl.searchParams.has('order'))) {
                currentUrl.searchParams.delete('order');
            } else {
                currentUrl.searchParams.set('order', 'desc');
            }
            document.location.href = currentUrl.href;
        });

        $('.accept-filters').on('click', function () {
            let filters = $('.filters').serializeArray();
            let currentUrl = new URL(document.location.href);
            $.each(filters, function (id, filter) {
                if (filter.value !== '') {
                    currentUrl.searchParams.set(filter.name, filter.value);
                } else {
                    currentUrl.searchParams.delete(filter.name);
                }
            });
            currentUrl.searchParams.delete('page');
            document.location.href = currentUrl.href;
        });

        $('.reset-filters').on('click', function () {
            let filters = $('.filters').serializeArray();
            let currentUrl = new URL(document.location.href);
            $.each(filters, function (id, filter) {
                currentUrl.searchParams.delete(filter.name);
            });
            currentUrl.searchParams.delete('page');
            document.location.href = currentUrl.href;
        });

        $('.accept-search').on('click', function () {
            let s = $('.search-form input').val();
            let currentUrl = new URL(document.location.href);
            if (s !== '') {
                currentUrl.searchParams.set('s', s);
            } else {
                currentUrl.searchParams.delete('s');
            }
            currentUrl.searchParams.delete('page');
            document.location.href = currentUrl.href;
        });

        $('.reset-search').on('click', function () {
            let currentUrl = new URL(document.location.href);
            currentUrl.searchParams.delete('s');
            currentUrl.searchParams.delete('page');
            document.location.href = currentUrl.href;
        });
    </script>
@endpush