@extends('layouts.admin.theme')
@section('title', env('APP_NAME') . ' :: ' . __('Legislação'))

@push('scripts')
    <link rel="stylesheet" href="{{ asset('pmar/css/admin/legislacao/index.css') }}">
@endpush

@section('content')
    @include('errors.messageFlash')

    <div class="card shadow-sm border-0">
        @php $headLine = "<i class='fa-solid fa-scale-balanced'></i> " . __('Legislação municipal'); @endphp
        @include('components.buttons._headLineButtonsBackAdd', [
            'headLine'         => __($headLine),
            'routeBack'        => 'admin.dashboard',
            'routeBackParams'  => [],
            'nameBack'         => __('Voltar'),
            'routeAdd'         => 'admin.legislacao.create',
            'routeAddParams'   => $filterParams,
            'nameAdd'          => __('Nova legislação'),
            'permission'       => 'GERENCIADOR_DE_LEGISLACAO',
        ])

        <div class="card-body p-0">

            {{-- ── Atalhos de navegação ── --}}
            @if (auth()->user()->getPermissaoDetalhes('GERENCIADOR_DE_LEGISLACAO')['visualizar'])
                <div class="leg-nav-bar d-flex flex-wrap gap-2 mt-3">
                    <a href="{{ route('admin.legislacao.portarias.index') }}" class="btn btn-outline-primary btn-sm">
                        <i class="fa-solid fa-file-signature me-1" aria-hidden="true"></i>{{ __('Portarias') }}
                    </a>
                    <a href="{{ route('admin.legislacao.cadastros.index', ['aba' => 'tipos'] + $filterParams) }}"
                        class="btn btn-outline-secondary btn-sm">
                        <i class="fa-solid fa-tags me-1" aria-hidden="true"></i>{{ __('Tipos') }}
                    </a>
                    <a href="{{ route('admin.legislacao.cadastros.index', ['aba' => 'categorias'] + $filterParams) }}"
                        class="btn btn-outline-secondary btn-sm">
                        <i class="fa-solid fa-folder me-1" aria-hidden="true"></i>{{ __('Categorias') }}
                    </a>
                    <a href="{{ route('admin.legislacao.cadastros.index', ['aba' => 'cargos'] + $filterParams) }}"
                        class="btn btn-outline-secondary btn-sm">
                        <i class="fa-solid fa-id-badge me-1" aria-hidden="true"></i>{{ __('Cargos') }}
                    </a>
                    <a href="{{ route('admin.legislacao.cadastros.index', ['aba' => 'autores'] + $filterParams) }}"
                        class="btn btn-outline-secondary btn-sm">
                        <i class="fa-solid fa-user me-1" aria-hidden="true"></i>{{ __('Autores') }}
                    </a>
                </div>
            @endif

            <div class="p-3 p-md-4">

                {{-- ── Painel de filtros ── --}}
                <form method="get" action="{{ route('admin.legislacao.index') }}" class="leg-filter-panel mb-4">
                    @if (request()->filled('sort_by'))
                        <input type="hidden" name="sort_by" value="{{ request('sort_by') }}">
                    @endif
                    @if (request()->filled('sort_dir'))
                        <input type="hidden" name="sort_dir" value="{{ request('sort_dir') }}">
                    @endif
                    <div class="d-flex justify-content-end mb-3">
                        <span class="badge bg-primary leg-results-badge">
                            <i class="fa-solid fa-scale-balanced me-1" aria-hidden="true"></i>
                            {{ __('Registros encontrados') }}:
                            <strong>{{ number_format($legislacoes->total(), 0, ',', '.') }}</strong>
                        </span>
                    </div>
                    <div class="row g-3 align-items-end">
                        <div class="col-12 col-sm-6 col-lg-2">
                            <label for="leg-filtro-ano" class="form-label">
                                <i class="fa-solid fa-calendar-days me-1 text-muted" aria-hidden="true"></i>{{ __('Ano de publicação') }}
                            </label>
                            <select id="leg-filtro-ano" name="ano" class="form-select">
                                <option value="">{{ __('Todos') }}</option>
                                @foreach ($anos as $ano)
                                    <option value="{{ $ano }}" @selected((string) $anoSelecionado === (string) $ano)>{{ $ano }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col-12 col-sm-6 col-lg-3">
                            <label for="leg-filtro-tipo" class="form-label">
                                <i class="fa-solid fa-tags me-1 text-muted" aria-hidden="true"></i>{{ __('Tipo') }}
                            </label>
                            <select id="leg-filtro-tipo" name="tipo" class="form-select">
                                <option value="">{{ __('Todos') }}</option>
                                @foreach ($tipos as $tipo)
                                    <option value="{{ $tipo->id_tipo_legislacao }}"
                                        @selected((string) ($filterParams['tipo'] ?? '') === (string) $tipo->id_tipo_legislacao)>
                                        {{ $tipo->ds_tipo_legislacao }}
                                    </option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col-12 col-sm-6 col-lg-3">
                            <label for="leg-filtro-status" class="form-label">
                                <i class="fa-solid fa-circle-check me-1 text-muted" aria-hidden="true"></i>{{ __('Status') }}
                            </label>
                            <select id="leg-filtro-status" name="status" class="form-select">
                                <option value="">{{ __('Todos') }}</option>
                                @foreach ($statusOpcoes as $valor => $rotulo)
                                    <option value="{{ $valor }}"
                                        @selected((string) ($filterParams['status'] ?? '') === (string) $valor)>
                                        {{ $rotulo }}
                                    </option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col-12 col-lg-4">
                            <label for="leg-filtro-q" class="form-label">
                                <i class="fa-solid fa-magnifying-glass me-1 text-muted" aria-hidden="true"></i>{{ __('Buscar') }}
                            </label>
                            <input id="leg-filtro-q" type="text" class="form-control" name="q"
                                value="{{ $filterParams['q'] ?? '' }}"
                                placeholder="{{ __('Número ou ementa…') }}"
                                maxlength="255"
                                autocomplete="off">
                        </div>
                    </div>
                    <div class="leg-filter-actions d-flex flex-wrap justify-content-end align-items-center gap-2 mt-3">
                        <button class="btn btn-outline-success" type="submit">
                            <i class="fa-solid fa-filter me-1" aria-hidden="true"></i>{{ __('Filtrar') }}
                        </button>
                        <a href="{{ route('admin.legislacao.index', ['ano' => '', 'tipo' => '', 'status' => '', 'q' => '']) }}"
                           class="btn btn-outline-secondary">{{ __('Limpar') }}</a>
                    </div>
                </form>

                {{-- ── Tabela ── --}}
                <div class="leg-table-section">
                <div class="row">
                    <div class="col-12">
                        <div class="table-responsive">
                            <table class="table table-bordered table-hover table-striped align-middle text-center">
                                <thead class="table-light">
                                    <tr>
                                        <th>#</th>
                                        <th>
                                            @include('components.legislacao._listagem_sort_link', [
                                                'route' => 'admin.legislacao.index',
                                                'column' => 'tipo',
                                                'label' => __('Tipo'),
                                            ])
                                        </th>
                                        <th>
                                            @include('components.legislacao._listagem_sort_link', [
                                                'route' => 'admin.legislacao.index',
                                                'column' => 'nr_legislacao',
                                                'label' => __('Nº'),
                                            ])
                                        </th>
                                        <th>
                                            @include('components.legislacao._listagem_sort_link', [
                                                'route' => 'admin.legislacao.index',
                                                'column' => 'ds_ementa',
                                                'label' => __('Ementa'),
                                            ])
                                        </th>
                                        <th>
                                            @include('components.legislacao._listagem_sort_link', [
                                                'route' => 'admin.legislacao.index',
                                                'column' => 'dt_publicacao',
                                                'label' => __('Publicação'),
                                            ])
                                        </th>
                                        <th>{{ __('BO') }}</th>
                                        <th>{{ __('PDF') }}</th>
                                        <th>
                                            @include('components.legislacao._listagem_sort_link', [
                                                'route' => 'admin.legislacao.index',
                                                'column' => 'cd_status',
                                                'label' => __('Status'),
                                            ])
                                        </th>
                                        <th>{{ __('Ações') }}</th>
                                    </tr>
                                </thead>
                                <tbody>
                        @php $index = $legislacoes->firstItem(); @endphp
                        @forelse ($legislacoes as $item)
                            <tr>
                                {{-- Índice --}}
                                <td class="leg-idx">{{ $index }}</td>

                                {{-- Tipo --}}
                                <td>
                                    @if ($item->tipo->ds_tipo_legislacao ?? false)
                                        <span class="badge-tipo">{{ $item->tipo->ds_tipo_legislacao }}</span>
                                    @else
                                        <span class="text-muted">—</span>
                                    @endif
                                </td>

                                {{-- Número --}}
                                <td title="{{ $item->ds_ementa }}">
                                    <span class="leg-nr">{{ $item->nr_legislacao }}</span>
                                </td>

                                {{-- Ementa --}}
                                <td class="leg-ementa-cell">
                                    <span class="leg-ementa d-block">
                                        {{ \Illuminate\Support\Str::limit($item->ds_ementa ?? '', 60) }}
                                    </span>
                                </td>

                                {{-- Data de publicação --}}
                                <td class="leg-date">
                                    @if ($item->dt_publicacao)
                                        {{ $item->dt_publicacao->format('d/m/Y') }}
                                    @else
                                        <span class="text-muted">—</span>
                                    @endif
                                </td>

                                {{-- Boletim Oficial --}}
                                <td class="leg-bo-cell">
                                    @php
                                        $temBoPrincipal  = (bool) $item->boletim;
                                        $temBoRetificacao = $item->retificacoes->contains(fn ($r) => (bool) $r->boletim);
                                    @endphp

                                    @if ($item->boletim)
                                        <div class="mb-1">
                                            @include('components.legislacao._boletimNumeroLink', ['boletim' => $item->boletim])
                                        </div>
                                    @endif

                                    @foreach ($item->retificacoes as $ret)
                                        @if ($ret->boletim)
                                            <div class="d-flex flex-wrap align-items-center gap-1 @if (! $loop->first) mt-1 @endif">
                                                <span class="badge rounded-pill bg-warning-subtle text-dark small">
                                                    {{ (int) $ret->cd_tipo === 1 ? __('Errata') : __('Republicação') }}
                                                </span>
                                                @include('components.legislacao._boletimNumeroLink', ['boletim' => $ret->boletim])
                                            </div>
                                        @endif
                                    @endforeach

                                    @if (! $temBoPrincipal && ! $temBoRetificacao)
                                        <span class="text-muted">—</span>
                                    @endif
                                </td>

                                {{-- PDF da legislação --}}
                                <td>
                                    @if ($item->public_pdf_url)
                                        <a href="{{ $item->public_pdf_url }}" target="_blank" rel="noopener noreferrer"
                                           class="btn btn-sm btn-outline-danger">
                                            <i class="fa-solid fa-file-pdf" aria-hidden="true"></i>
                                        </a>
                                    @else
                                        <span class="text-muted">—</span>
                                    @endif
                                </td>

                                {{-- Status --}}
                                <td>
                                    @if ((int) $item->cd_status === 1)
                                        <span class="badge-status badge-status-review">{{ __('Aguardando revisão') }}</span>
                                    @elseif ((int) $item->cd_status === 2)
                                        <span class="badge-status badge-status-pending">{{ __('Pendente') }}</span>
                                    @else
                                        <span class="badge-status badge-status-published">{{ __('Publicado') }}</span>
                                    @endif
                                </td>

                                {{-- Ações --}}
                                <td>
                                    <div class="leg-actions d-flex justify-content-center gap-2">
                                        @if (auth()->user()->getPermissaoDetalhes('GERENCIADOR_DE_LEGISLACAO')['editar'])
                                            <a class="btn btn-sm btn-warning"
                                               href="{{ route('admin.legislacao.edit', [$item->id_legislacao] + $filterParams) }}"
                                               title="{{ __('Editar') }}">
                                                <i class="fa-solid fa-pen-to-square" aria-hidden="true"></i>
                                            </a>
                                        @endif
                                        @if (auth()->user()->getPermissaoDetalhes('GERENCIADOR_DE_LEGISLACAO')['excluir'])
                                            <form class="d-inline"
                                                  action="{{ route('admin.legislacao.destroy', $item->id_legislacao) }}"
                                                  method="post"
                                                  onsubmit="return confirmDelete(this)">
                                                @csrf
                                                @method('delete')
                                                @foreach ($filterParams as $key => $value)
                                                    @if ($value !== null && $value !== '')
                                                        <input type="hidden" name="{{ $key }}" value="{{ $value }}">
                                                    @endif
                                                @endforeach
                                                <input type="hidden" name="confirm"
                                                    value="{{ __('* Este registro será excluído e esta ação não poderá ser desfeita, deseja continuar?') }}">
                                                <button type="submit" class="btn btn-sm btn-danger" title="{{ __('Excluir') }}">
                                                    <i class="fa-solid fa-trash" aria-hidden="true"></i>
                                                </button>
                                            </form>
                                        @endif
                                    </div>
                                </td>
                            </tr>
                            @php $index++; @endphp
                        @empty
                            <tr class="leg-empty">
                                <td colspan="9" class="text-center">
                                    <i class="fa-solid fa-scale-balanced leg-empty-icon" aria-hidden="true"></i>
                                    {{ __('Nenhum registro encontrado.') }}
                                </td>
                            </tr>
                        @endforelse
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <div class="col-12 my-3">
                        <div class="d-flex justify-content-center">
                            {!! $legislacoes->links() !!}
                        </div>
                    </div>
                </div>
                </div>

            </div>{{-- /p-3 --}}
        </div>{{-- /card-body --}}
    </div>{{-- /card --}}
@endsection
