@extends('layouts.admin.theme')
@section('title', env('APP_NAME') . ' :: ' . $timeline->name)
@push('scripts')
    <link rel="stylesheet" href="{{ asset('pmar/css/linhas-do-tempo.css') }}">
@endpush
@section('content')

@php
    $perm = auth()->user()->getPermissaoDetalhes('GERENCIADOR_DE_LINHAS_DO_TEMPO');
    $timelineAttachments = $attachmentsByEntity->get(\App\Enums\Accounts\LinhasDoTempoAttachmentEntity::Timeline->value . ':' . $timeline->id, collect());
@endphp

<div id="linhas-do-tempo-detail"
     class="card shadow-sm border-0"
     data-timeline-id="{{ $timeline->id }}"
     data-csrf="{{ csrf_token() }}"
     data-url-point-store="{{ route('admin.contaAngra.linhasDoTempo.pontos.store', $timeline) }}"
     data-url-points-base="{{ route('admin.contaAngra.linhasDoTempo.pontos.store', $timeline) }}"
     data-url-draft-point-get="{{ route('admin.contaAngra.linhasDoTempo.pontos.draft.create.show', $timeline) }}"
     data-url-draft-point-post="{{ route('admin.contaAngra.linhasDoTempo.pontos.draft.create', $timeline) }}"
     data-url-draft-point-delete="{{ route('admin.contaAngra.linhasDoTempo.pontos.draft.create.destroy', $timeline) }}"
     data-url-export-pdf="{{ route('admin.contaAngra.linhasDoTempo.export.pdf', $timeline) }}"
     data-url-export-excel="{{ route('admin.contaAngra.linhasDoTempo.export.excel', $timeline) }}"
     data-msg-saved="{{ __('Rascunho salvo') }}"
     data-msg-point-added="{{ __('Ponto histórico adicionado.') }}"
     data-msg-point-deleted="{{ __('Ponto histórico excluído.') }}"
     data-msg-note-saved="{{ __('Nota salva.') }}"
     data-label-delete="{{ __('Excluir') }}"
     data-confirm-delete-note="{{ __('Excluir esta nota?') }}">

    @php $headLine = "<i class='fa-solid fa-timeline'></i> " . e($timeline->name); @endphp

    @include('components.buttons._headLineButtonsBackAdd', [
        'headLine' => $headLine,
        'routeBack' => 'admin.contaAngra.linhasDoTempo.index',
        'routeBackParams' => request()->only(['q', 'status', 'date_from', 'date_to', 'tag', 'sort', 'dir', 'view']),
        'nameBack' => __('Lista'),
        'routeAdd' => $perm['editar'] ? 'admin.contaAngra.linhasDoTempo.edit' : null,
        'routeAddParams' => $perm['editar'] ? ['timeline' => $timeline] : [],
        'nameAdd' => __('Editar linha'),
        'permission' => 'GERENCIADOR_DE_LINHAS_DO_TEMPO',
    ])

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

        <div class="d-flex flex-wrap gap-2 mb-3 align-items-center">
            @if ($perm['visualizar'])
                <a class="btn btn-outline-secondary btn-sm" href="{{ route('admin.contaAngra.linhasDoTempo.export.pdf', $timeline) }}">{{ __('Exportar PDF') }}</a>
                <a class="btn btn-outline-secondary btn-sm" href="{{ route('admin.contaAngra.linhasDoTempo.export.excel', $timeline) }}">{{ __('Exportar Excel') }}</a>
            @endif
            @if ($perm['editar'] && $timeline->status === 'active')
                <form method="post" action="{{ route('admin.contaAngra.linhasDoTempo.arquivar', $timeline) }}" class="d-inline">
                    @csrf
                    <button type="submit" class="btn btn-outline-warning btn-sm">{{ __('Arquivar') }}</button>
                </form>
            @endif
        </div>

        <nav class="lt-timeline-rail border-bottom bg-body shadow-sm mb-4 px-2" aria-label="{{ __('Navegação entre pontos históricos') }}">
            <div class="d-flex align-items-center gap-2">
                <button type="button" class="btn btn-sm btn-outline-secondary lt-scroll-left" aria-label="{{ __('Rolar para a esquerda') }}">&laquo;</button>
                <div class="lt-timeline-track flex-grow-1" id="ltTimelineTrack">
                    @foreach($timeline->historicalPoints as $p)
                        <div class="lt-marker" data-anchor="ponto-{{ $p->id }}">
                            <a class="btn btn-sm btn-outline-primary lt-anchor-link" href="#ponto-{{ $p->id }}" title="{{ e($p->name) }}">{{ $p->event_date?->format('d/m/y') }}</a>
                        </div>
                    @endforeach
                    @if($perm['adicionar'])
                        <div class="lt-marker">
                            <button type="button" class="btn btn-sm btn-success" data-bs-toggle="modal" data-bs-target="#ltModalPoint" id="ltBtnAddPoint">{{ __('Adicionar ponto') }}</button>
                        </div>
                    @endif
                </div>
                <button type="button" class="btn btn-sm btn-outline-secondary lt-scroll-right" aria-label="{{ __('Rolar para a direita') }}">&raquo;</button>
            </div>
        </nav>

        <section class="mb-3 small text-muted" aria-label="{{ __('Dados da linha do tempo') }}">
            <div>{{ __('Marco zero') }}: {{ $timeline->event_date?->format('d/m/Y') }}</div>
            @if($timeline->description)
                <div>{{ __('Descrição / resumo') }}: {{ $timeline->description }}</div>
            @endif
        </section>

        <div class="mb-3">
            <h2 class="h6">{{ __('Processo') }}</h2>
            <div class="border rounded p-3 bg-light">{!! $timeline->process_text !!}</div>
        </div>

        @if($timelineAttachments->isNotEmpty())
            <div class="mb-3">
                <h2 class="h6">{{ __('Anexos da linha') }}</h2>
                <ul class="list-unstyled row row-cols-1 row-cols-md-2 g-2">
                    @foreach($timelineAttachments as $att)
                        <li class="col">
                            <div class="border rounded p-2 d-flex justify-content-between align-items-center">
                                <span class="text-truncate me-2" title="{{ e($att->original_name) }}">{{ e($att->original_name) }}</span>
                                <a class="btn btn-sm btn-outline-primary" href="{{ route('admin.contaAngra.linhasDoTempo.attachments.download', [$timeline, $att]) }}">{{ __('Baixar') }}</a>
                            </div>
                        </li>
                    @endforeach
                </ul>
            </div>
        @endif

        <div id="ltPointsContainer">
        @foreach($timeline->historicalPoints as $idx => $p)
            @php
                $pointAtt = $attachmentsByEntity->get(\App\Enums\Accounts\LinhasDoTempoAttachmentEntity::HistoricalPoint->value . ':' . $p->id, collect());
            @endphp
            <section id="ponto-{{ $p->id }}" class="lt-point-block border rounded mb-4 p-3" data-point-id="{{ $p->id }}" tabindex="-1">
                <header class="d-flex flex-wrap justify-content-between align-items-start gap-2 mb-2">
                    <div>
                        <span class="badge bg-secondary me-1">{{ __('Ponto') }} {{ $idx + 1 }} {{ __('de') }} {{ $timeline->historicalPoints->count() }}</span>
                        <h2 class="h5 d-inline">{{ $p->name }}</h2>
                        <div class="small text-muted">{{ $p->event_date?->format('d/m/Y H:i') }}</div>
                    </div>
                    <div class="dropdown">
                        <button class="btn btn-sm btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false" aria-label="{{ __('Ações do ponto') }}">⋮</button>
                        <ul class="dropdown-menu dropdown-menu-end">
                            @if($perm['editar'])
                                <li><button type="button" class="dropdown-item lt-edit-point" data-point-id="{{ $p->id }}" data-bs-toggle="modal" data-bs-target="#ltModalPoint">{{ __('Editar') }}</button></li>
                            @endif
                            @if($perm['excluir'])
                                <li>
                                    <button type="button" class="dropdown-item text-danger lt-delete-point" data-point-id="{{ $p->id }}" data-bs-toggle="modal" data-bs-target="#ltModalDeletePoint">{{ __('Excluir') }}</button>
                                </li>
                            @endif
                        </ul>
                    </div>
                </header>
                <h3 class="h6">{{ __('Processo') }}</h3>
                <div class="mb-3">{!! $p->process_text !!}</div>
                @if($pointAtt->isNotEmpty())
                    <div class="mb-3">
                        <h3 class="h6">{{ __('Anexos') }}</h3>
                        <div class="row row-cols-1 row-cols-md-2 g-2">
                            @foreach($pointAtt as $att)
                                <div class="col">
                                    <div class="border rounded p-2 d-flex justify-content-between align-items-center">
                                        <span class="text-truncate me-2">{{ e($att->original_name) }}</span>
                                        <a class="btn btn-sm btn-outline-primary" href="{{ route('admin.contaAngra.linhasDoTempo.attachments.download', [$timeline, $att]) }}">{{ __('Baixar') }}</a>
                                    </div>
                                </div>
                            @endforeach
                        </div>
                    </div>
                @endif
                @include('components.linhasDoTempo.offcanvas-notas-ponto', [
                    'timeline' => $timeline,
                    'point' => $p,
                    'perm' => $perm,
                ])
            </section>
        @endforeach

        @if($timeline->historicalPoints->isEmpty() && $perm['adicionar'])
            <p class="text-muted" id="ltEmptyPointsMsg">{{ __('Nenhum ponto histórico ainda. Use o botão “Adicionar ponto” na faixa acima.') }}</p>
        @endif
        </div>

        @if($perm['excluir'])
            <div class="mt-4 border-top pt-3">
                <button type="button" class="btn btn-outline-danger" data-bs-toggle="modal" data-bs-target="#ltModalDeleteTimeline">{{ __('Excluir linha do tempo') }}</button>
            </div>
        @endif
    </div>
</div>

@if($perm['adicionar'])
<div class="modal fade" id="ltModalPoint" tabindex="-1" aria-labelledby="ltModalPointLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header">
                <h2 class="modal-title h5" id="ltModalPointLabel">{{ __('Ponto histórico') }}</h2>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="{{ __('Fechar') }}"></button>
            </div>
            <div class="modal-body">
                <form id="ltPointForm">
                    <input type="hidden" id="ltPointId" value="">
                    <div class="mb-3">
                        <label class="form-label" for="ltPointName">{{ __('Nome') }} <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="ltPointName" maxlength="150" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label" for="ltPointDate">{{ __('Data de acontecimento') }} <span class="text-danger">*</span></label>
                        <input type="datetime-local" class="form-control" id="ltPointDate" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label" for="ltPointProcess">{{ __('Processo') }} <span class="text-danger">*</span></label>
                        <textarea class="form-control" id="ltPointProcess" rows="8" required></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label" for="ltPointFiles">{{ __('Anexos') }}</label>
                        <input type="file" class="form-control" id="ltPointFiles" multiple accept=".pdf,.png,.jpg,.jpeg,.gif,.webp,.xlsx,.xls,.ods,.csv,.docx,.doc">
                    </div>
                    <span class="small text-muted d-block mb-2" id="ltPointAutosave" aria-live="polite"></span>
                    <button type="submit" class="btn btn-primary">{{ __('Salvar ponto') }}</button>
                </form>
            </div>
        </div>
    </div>
</div>
@endif

@if($perm['excluir'])
<div class="modal fade" id="ltModalDeletePoint" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h2 class="modal-title h5">{{ __('Excluir ponto histórico') }}</h2>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="{{ __('Fechar') }}"></button>
            </div>
            <div class="modal-body">
                <p>{{ __('Deseja realmente excluir este ponto?') }}</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">{{ __('Cancelar') }}</button>
                <button type="button" class="btn btn-danger" id="ltConfirmDeletePoint">{{ __('Excluir') }}</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="ltModalDeleteTimeline" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="post" action="{{ route('admin.contaAngra.linhasDoTempo.destroy', $timeline) }}">
                @csrf
                @method('delete')
                <div class="modal-header">
                    <h2 class="modal-title h5">{{ __('Excluir linha do tempo') }}</h2>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="{{ __('Fechar') }}"></button>
                </div>
                <div class="modal-body">
                    <p>{{ __('Digite o nome exato da linha do tempo para confirmar.') }}</p>
                    <label class="form-label" for="confirm_name">{{ __('Nome') }}</label>
                    <input type="text" class="form-control" name="confirm_name" id="confirm_name" autocomplete="off" required>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">{{ __('Cancelar') }}</button>
                    <button type="submit" class="btn btn-danger">{{ __('Excluir definitivamente') }}</button>
                </div>
            </form>
        </div>
    </div>
</div>
@endif

<script type="application/json" id="lt-points-data">@json($pointsData)</script>

@endsection

@push('after-scripts')
    <script src="{{ asset('pmar/js/linhas-do-tempo.js') }}"></script>
@endpush
