@extends('layouts.admin.theme')
@section("title", env("APP_NAME") . " :: " . __("Lista de Repositórios"))
@section('content')

    <div class="card shadow-sm">

        @php $headLine = "<i class='fa-solid fa-box-archive'></i> " . __("Lista de Arquivos no Repositório"); @endphp

        @include('components.buttons._headLineButtonsBackAdd', [
            'headLine' => $headLine,
            'routeAdd' => 'admin.repositorio.create',
            'routeAddParams' => [],
            'nameAdd' => __('Novo Arquivo'),
            "permission" => "GERENCIADOR_DO_REPOSITORIO_DO_PORTAL",
        ])

        <div class="card-body">
            @include("errors.messageFlash")

            @php
                $permissaoDetalhes = auth()->user()->getPermissaoDetalhes('GERENCIADOR_DO_REPOSITORIO_DO_PORTAL');
                $canEdit = $permissaoDetalhes['editar'] ?? false;
                $canDelete = $permissaoDetalhes['excluir'] ?? false;
            @endphp

            <x-tables._table :thead="[
                __('Arquivo'),
                __('Data de Publicação'),
                __('Título'),
                __('Sumário'),
                __('URL'),
                __('Status'),
            ]" :pagination="$repositories->links()">
                <x-slot name="body">
                    @php $index = 0; @endphp
                    @forelse($repositories as $repository)
                        <tr>
                            <td>
                                @php
                                    $extensoesImagem = ['jpg', 'jpeg', 'png', 'gif'];
                                    $extensao = pathinfo($repository->url, PATHINFO_EXTENSION);
                                @endphp
                                @if (in_array(strtolower($extensao), $extensoesImagem))
                                    @include('components.tables._openPhoto', [
                                        'asset' => $repository->url,
                                        'index' => $index,
                                        'alt' => $repository->title,
                                        'title' => $repository->title,
                                        'text' => __('Visualizar arquivo'),
                                        'style' => 'width: 90px;'
                                    ])
                                @else
                                    <a href="{{ asset($repository->url) }}" class="text-primary" target="_blank" download>
                                        <i class="fa-solid fa-download"></i> {{ __('Baixar arquivo') }}
                                    </a>
                                @endif
                            </td>
                            <td>
                                {{ date("d/m/Y", strtotime($repository->created_at)) }}
                            </td>
                            <td>
                                {{ $repository->title }}<br>
                                @if($canEdit)
                                    <a class="text-warning text-decoration-none p-1 d-inline fs-5"
                                        href='{{ route("admin.repositorio.edit", $repository->id)}}'
                                        title="{{ __('Editar') }}">
                                        <span class="material-symbols-outlined" data-bs-toggle="tooltip" data-bs-placement="top"
                                            title="{{ __('Editar') }}">
                                            <i class="fa-solid fa-pen-to-square"></i>
                                        </span>
                                    </a>
                                @else
                                    <span class="text-muted">-</span>
                                @endif
                                @if($canDelete)
                                    <form class="del d-inline" action="{{ route("admin.repositorio.destroy", $repository->id)}}"
                                        method="post" onsubmit="return confirmDelete(this)">
                                        @csrf
                                        @method('delete')
                                        <input type="hidden" name="page" value="{{ request()->input('page', 1) }}">
                                        <input type="hidden" name="confirm"
                                            value="{{ __("* Este arquivo será excluído e esta ação não poderá ser desfeita, deseja continuar?") }}" />
                                        <button class="text-danger text-decoration-none border-0 bg-transparent fs-5" type="submit"
                                            title="{{ __('Excluir') }}">
                                            <span class="material-symbols-outlined" data-bs-toggle="tooltip" data-bs-placement="top"
                                                title="{{ __('Excluir') }}">
                                                <i class="fa-solid fa-trash"></i>
                                            </span>
                                        </button>
                                    </form>
                                @else
                                    <span class="text-muted">-</span>
                                @endif
                            </td>
                            <td>{{ $repository->summary ?? '-' }}</td>
                            <td>
                                @php
                                    $fileUrl = asset($repository->url);
                                    $urlDisplay = strlen($fileUrl) > 40 ? substr($fileUrl, 0, 40) . '...' : $fileUrl;
                                @endphp
                                <div class="d-flex align-items-center gap-2 flex-wrap">
                                    <a class="text-primary text-decoration-none"
                                       href="{{ $fileUrl }}"
                                       target="_blank"
                                       title="{{ __('Abrir arquivo em nova aba') }}"
                                       rel="noopener noreferrer"
                                       data-bs-toggle="tooltip">
                                        <i class="fa-solid fa-external-link-alt"></i>
                                    </a>
                                    <a class="text-dark text-decoration-none d-inline fs-5 copy-url-btn"
                                       href="javascript:void(0);"
                                       onclick="copyRepositorioUrl('{{ $fileUrl }}', this)"
                                       title="{{ __('Copiar URL do arquivo') }}"
                                       data-url="{{ $fileUrl }}"
                                       data-bs-toggle="tooltip"
                                       style="cursor: pointer;">
                                        <i class="fa-solid fa-copy"></i>
                                    </a>
                                    <small class="text-muted" style="font-size: 0.7rem; word-break: break-all;">
                                        <span class="url-preview" title="{{ $fileUrl }}" data-bs-toggle="tooltip">{{ $urlDisplay }}</span>
                                    </small>
                                </div>
                            </td>
                            <td>
                                @if($canEdit)
                                    <form id="{{ "checkStatus_" . $index }}"
                                        action="{{ route("admin.repositorio.status", $repository->id)}}" method="post">
                                        @csrf
                                        @if($repository->status == "ATIVADO")
                                            <div class="form-check form-switch">
                                                <input type="hidden" name="checkStatus" value="DESATIVADO">
                                                <input class="form-check-input" type="checkbox" checked
                                                    onclick="javascript:$('#{{ "checkStatus_" . $index }}').submit()">
                                            </div>
                                        @else
                                            <div class="form-check form-switch">
                                                <input type="hidden" name="checkStatus" value="ATIVADO">
                                                <input class="form-check-input" type="checkbox"
                                                    onclick="javascript:$('#{{ "checkStatus_" . $index }}').submit()">
                                            </div>
                                        @endif
                                    </form>
                                @else
                                    <span class="badge {{ $repository->status === 'ATIVADO' ? 'bg-success' : 'bg-secondary' }}">
                                        {{ __($repository->status === 'ATIVADO' ? 'Ativado' : 'Desativado') }}
                                    </span>
                                @endif
                            </td>
                        </tr>
                        @php $index++; @endphp
                    @empty
                        <tr>
                            <td colspan="6">
                                <p>{{ __('Nenhum arquivo encontrado.') }}</p>
                            </td>
                        </tr>
                    @endforelse
                </x-slot>
            </x-tables._table>
        </div>
    </div>

    @push('scripts')
        <script src="{{ asset('pmar/js/repositorio.js') }}"></script>
        <script>
            // Inicializa tooltips do Bootstrap
            document.addEventListener('DOMContentLoaded', function() {
                var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
                var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
                    return new bootstrap.Tooltip(tooltipTriggerEl);
                });

                // Exibe mensagem de sucesso vinda do sessionStorage
                var successMessage = sessionStorage.getItem('success_message');
                if (successMessage) {
                    // Remove a mensagem do sessionStorage
                    sessionStorage.removeItem('success_message');
                    
                    // Cria e exibe o alerta de sucesso
                    var alertDiv = document.createElement('div');
                    alertDiv.className = 'alert alert-success alert-dismissible fade show';
                    alertDiv.setAttribute('role', 'alert');
                    alertDiv.innerHTML = successMessage + '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>';
                    
                    // Insere o alerta após o include do messageFlash
                    var cardBody = document.querySelector('.card-body');
                    var messageFlashContainer = cardBody.querySelector('.alert');
                    if (messageFlashContainer) {
                        messageFlashContainer.parentNode.insertBefore(alertDiv, messageFlashContainer.nextSibling);
                    } else {
                        cardBody.insertBefore(alertDiv, cardBody.firstChild);
                    }
                }
            });
        </script>
    @endpush
@endsection
