@extends('layouts.admin.theme')
@section('title', env('APP_NAME') . ' :: ' . __('Contratos'))

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

    <div class="card shadow-sm">
        @php $headLine = "<i class='fa-solid fa-file-contract'></i> " . __('Contratos'); @endphp
        @include('components.buttons._headLineButtonsBackAdd', [
            'headLine' => __($headLine),
            'routeBack' => 'admin.dashboard',
            'routeBackParams' => [],
            'nameBack' => __('Voltar'),
            'routeAdd' => 'admin.contratos.create',
            'routeAddParams' => request()->only(['q', 'ano', 'con_modalidade', 'con_status', 'page']),
            'nameAdd' => __('Novo contrato'),
            'permission' => 'GERENCIADOR_DE_CONTRATOS',
        ])

        <div class="card-body">
            <form method="get" class="row g-3 mb-3">
                <div class="col-12 col-lg-4">
                    <label class="form-label">{{ __('Buscar') }}</label>
                    <input type="text" class="form-control" name="q" value="{{ request('q') }}" placeholder="{{ __('Número, processo ou título') }}">
                </div>
                <div class="col-12 col-md-4 col-lg-2">
                    <label class="form-label">{{ __('Ano') }}</label>
                    <select class="form-select" name="ano">
                        <option value="">{{ __('Todos') }}</option>
                        @foreach($anosDisponiveis as $ano)
                            <option value="{{ $ano }}" @selected((string) request('ano') === (string) $ano)>{{ $ano }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-12 col-md-4 col-lg-3">
                    <label class="form-label">{{ __('Modalidade') }}</label>
                    <select class="form-select" name="con_modalidade">
                        <option value="">{{ __('Todas') }}</option>
                        @foreach(\App\Models\Contratos\Contrato::MODALIDADES as $key => $label)
                            <option value="{{ $key }}" @selected((string) request('con_modalidade') === (string) $key)>{{ __($label) }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-12 col-md-4 col-lg-3">
                    <label class="form-label">{{ __('Status') }}</label>
                    <select class="form-select" name="con_status">
                        <option value="">{{ __('Todos') }}</option>
                        @foreach(\App\Models\Contratos\Contrato::STATUS as $key => $label)
                            <option value="{{ $key }}" @selected((string) request('con_status') === (string) $key)>{{ __($label) }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-12 d-flex justify-content-end gap-2">
                    <a href="{{ route('admin.contratos.index') }}" class="btn btn-outline-secondary px-4">{{ __('Limpar filtros') }}</a>
                    <button class="btn btn-success px-4" type="submit">{{ __('Filtrar') }}</button>
                </div>
            </form>

            @php
                $formatDate = static function ($date): string {
                    if (empty($date)) {
                        return '-';
                    }

                    if ($date instanceof \Carbon\CarbonInterface) {
                        return $date->format('d/m/Y');
                    }
 
                    $dateString = (string) $date;

                    if (preg_match('/^\d{2}\/\d{2}\/\d{4}$/', $dateString)) {
                        return $dateString;
                    }

                    try {
                        return \Illuminate\Support\Carbon::parse($dateString)->format('d/m/Y');
                    } catch (\Throwable $exception) {
                        return '-';
                    }
                };
            @endphp

            <x-tables._table :thead="[__('Modalidade'), __('Número'), __('Ano'), __('Título'), __('Dt Início'), __('Dt Fim'), __('Anexos'), __('Dt Publicação'), __('Criado por'), __('Editado por'), __('Ações')]" :pagination="$registros->links()">
                <x-slot name="body">
                    @forelse($registros as $registro)
                        <tr>
                            <td>{{ $registro->modalidade_label ?: '-' }}</td>
                            <td>{{ $registro->con_numero ?: '-' }}</td>
                            <td>{{ $registro->con_ano ?: '-' }}</td>
                            <td>{{ $registro->con_titulo }}</td>
                            <td>{{ $formatDate($registro->con_dataini) }}</td>
                            <td>{{ $formatDate($registro->con_datafim) }}</td>
                            <td>{{ $registro->arquivos->count() }}</td>
                            <td>{{ $formatDate($registro->con_datapub) }}</td>
                            <td class="text-center">
                                @if($registro->criadoPor)
                                    <span data-bs-toggle="tooltip"
                                          data-bs-placement="top"
                                          data-bs-title="{{ $registro->criadoPor->name }} - {{ $registro->criadoPor->matriculation ?: __('Sem matrícula') }}"
                                          class="text-secondary fs-5">
                                        <i class="fa-solid fa-circle-user"></i>
                                    </span>
                                @else
                                    <span class="text-muted">-</span>
                                @endif
                            </td>
                            <td class="text-center">
                                @if($registro->editadoPor)
                                    <span data-bs-toggle="tooltip"
                                          data-bs-placement="top"
                                          data-bs-title="{{ $registro->editadoPor->name }} - {{ $registro->editadoPor->matriculation ?: __('Sem matrícula') }}"
                                          class="text-secondary fs-5">
                                        <i class="fa-solid fa-circle-user"></i>
                                    </span>
                                @else
                                    <span class="text-muted">-</span>
                                @endif
                            </td>
                            <td>
                                <div class="d-flex justify-content-center gap-2">
                                    <a class="btn btn-sm btn-secondary" href="{{ route('admin.contratos.show', [$registro->id_contrato] + request()->only(['q', 'ano', 'con_modalidade', 'con_status', 'page'])) }}">
                                        <i class="fa-solid fa-eye"></i>
                                    </a>
                                    @if(auth()->user()->getPermissaoDetalhes('GERENCIADOR_DE_CONTRATOS')['editar'])
                                        <a class="btn btn-sm btn-warning" href="{{ route('admin.contratos.edit', [$registro->id_contrato] + request()->only(['q', 'ano', 'con_modalidade', 'con_status', 'page'])) }}">
                                            <i class="fa-solid fa-pen-to-square"></i>
                                        </a>
                                        <a class="btn btn-sm btn-primary" href="{{ route('admin.contratos.arquivos', [$registro->id_contrato] + request()->only(['q', 'ano', 'con_modalidade', 'con_status', 'page'])) }}">
                                            <i class="fa-solid fa-file-lines"></i>
                                        </a>
                                    @endif
                                    @if(auth()->user()->getPermissaoDetalhes('GERENCIADOR_DE_CONTRATOS')['excluir'])
                                        <form class="d-inline" action="{{ route('admin.contratos.destroy', $registro->id_contrato) }}" method="post" onsubmit="return confirmDelete(this)">
                                            @csrf
                                            @method('delete')
                                            @foreach(request()->only(['q', 'ano', 'con_modalidade', 'con_status', 'page']) as $key => $value)
                                                <input type="hidden" name="{{ $key }}" value="{{ $value }}">
                                            @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">
                                                <i class="fa-solid fa-trash"></i>
                                            </button>
                                        </form>
                                    @endif
                                </div>
                            </td>
                        </tr>
                    @empty
                        <tr>
                            <td colspan="11" class="text-center">{{ __('Nenhum registro encontrado.') }}</td>
                        </tr>
                    @endforelse
                </x-slot>
            </x-tables._table>
        </div>
    </div>
@push('after-scripts')
    <script src="{{ asset('pmar/js/admin/contratos/index.js') }}"></script>
@endpush
@endsection
