@extends('layouts.admin.theme')
@section('title', env('APP_NAME') . ' :: ' . __('Cronogramas'))
@push('scripts')
    <link rel="stylesheet" href="{{ asset('pmar/css/cronogramas.css') }}">
@endpush
@section('content')

@php
    $listQuery = $filterParams ?? [];
    $canEdit = ($perm['editar'] ?? false);
    $canDelete = ($perm['excluir'] ?? false);
    $viewTab = $viewTab ?? 'table';
@endphp

<div id="cronogramas-dashboard-app"
     class="card shadow-sm border-0"
     data-csrf="{{ csrf_token() }}"
     data-can-edit="{{ $canEdit ? '1' : '0' }}"
     data-can-delete="{{ $canDelete ? '1' : '0' }}"
     data-url-projects-bulk-destroy="{{ route('admin.cronogramas.projetos.arquivados.destroy') }}"
     data-msg-confirm-archive-project="{{ __('Arquivar este projeto? Ele será movido para a aba Arquivados.') }}"
     data-msg-confirm-delete-project="{{ __('Tem certeza que deseja excluir? Esta ação não poderá ser desfeita.') }}"
     data-msg-confirm-bulk-delete="{{ __('Excluir permanentemente :count projeto(s) selecionado(s)? Esta ação não poderá ser desfeita.') }}"
     data-msg-selected-one="{{ __('1 selecionado') }}"
     data-msg-selected-many="{{ __(':count selecionados') }}"
     data-msg-saved="{{ __('Operação realizada com sucesso.') }}"
     data-msg-error="{{ __('Não foi possível concluir. Tente novamente.') }}">

    @php $headLine = "<i class='fa-solid fa-chart-gantt'></i> " . e(__('Cronogramas')); @endphp

    @include('components.buttons._headLineButtonsBackAdd', [
        'headLine' => $headLine,
        'routeBack' => 'admin.dashboard',
        'routeBackParams' => [],
        'nameBack' => __('Voltar'),
        'routeAdd' => 'admin.cronogramas.projetos.create',
        'routeAddParams' => $listQuery,
        'nameAdd' => __('Novo projeto'),
        'permission' => 'GERENCIADOR_DE_CRONOGRAMAS',
    ])

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

        <div class="row g-3 mb-4" role="region" aria-label="{{ __('Indicadores') }}">
            <div class="col-6 col-md-4 col-lg-3">
                <div class="card border-0 bg-primary bg-opacity-10 h-100">
                    <div class="card-body text-center">
                        <div class="fs-4 fw-bold text-primary">{{ $indicators['total_projects'] }}</div>
                        <div class="small text-muted">{{ __('Total de projetos') }}</div>
                    </div>
                </div>
            </div>
            <div class="col-6 col-md-4 col-lg-3">
                <div class="card border-0 bg-info bg-opacity-10 h-100">
                    <div class="card-body text-center">
                        <div class="fs-4 fw-bold text-info">{{ $indicators['active_projects'] }}</div>
                        <div class="small text-muted">{{ __('Em andamento') }}</div>
                    </div>
                </div>
            </div>
            <div class="col-6 col-md-4 col-lg-3">
                <div class="card border-0 bg-success bg-opacity-10 h-100">
                    <div class="card-body text-center">
                        <div class="fs-4 fw-bold text-success">{{ $indicators['completed_projects'] }}</div>
                        <div class="small text-muted">{{ __('Concluídos') }}</div>
                    </div>
                </div>
            </div>
            <div class="col-6 col-md-4 col-lg-3">
                <div class="card border-0 bg-danger bg-opacity-10 h-100">
                    <div class="card-body text-center">
                        <div class="fs-4 fw-bold text-danger">{{ $indicators['overdue_projects'] }}</div>
                        <div class="small text-muted">{{ __('Atrasados') }}</div>
                    </div>
                </div>
            </div>
            <div class="col-6 col-md-4 col-lg-3">
                <div class="card border-0 bg-secondary bg-opacity-10 h-100">
                    <div class="card-body text-center">
                        <div class="fs-4 fw-bold">{{ $indicators['avg_completion'] }}%</div>
                        <div class="small text-muted">{{ __('Média de execução') }}</div>
                    </div>
                </div>
            </div>
            <div class="col-6 col-md-4 col-lg-3">
                <div class="card border-0 bg-warning bg-opacity-10 h-100">
                    <div class="card-body text-center">
                        <div class="fs-4 fw-bold text-warning">{{ $indicators['pending_activities'] }}</div>
                        <div class="small text-muted">{{ __('Atividades pendentes') }}</div>
                    </div>
                </div>
            </div>
            <div class="col-6 col-md-4 col-lg-3">
                <div class="card border-0 bg-danger bg-opacity-25 h-100">
                    <div class="card-body text-center">
                        <div class="fs-4 fw-bold text-danger">{{ $indicators['critical_activities'] }}</div>
                        <div class="small text-muted">{{ __('Atividades críticas') }}</div>
                    </div>
                </div>
            </div>
        </div>

        <ul class="nav nav-tabs cr-view-tabs mb-3" role="tablist">
            @php
                $tabs = [
                    'table' => ['icon' => 'fa-table-list', 'label' => __('Projetos')],
                    'archived' => ['icon' => 'fa-box-archive', 'label' => __('Arquivados'), 'badge' => $archivedCount ?? 0],
                ];
            @endphp
            @foreach($tabs as $key => $tab)
                <li class="nav-item" role="presentation">
                    <a class="nav-link @if($viewTab === $key) active @endif"
                       href="{{ route('admin.cronogramas.dashboard', array_merge($listQuery, ['tab' => $key])) }}">
                        <i class="fa-solid {{ $tab['icon'] }}"></i> {{ $tab['label'] }}
                        @if(! empty($tab['badge']))
                            <span class="badge bg-secondary ms-1" id="cr-archived-projects-tab-badge">{{ $tab['badge'] }}</span>
                        @endif
                    </a>
                </li>
            @endforeach
        </ul>

        <form method="get" action="{{ route('admin.cronogramas.dashboard') }}" class="row g-2 mb-3" role="search">
            <input type="hidden" name="tab" value="{{ $viewTab }}">
            <div class="col-md-3">
                <label class="form-label visually-hidden" for="flt_q">{{ __('Buscar') }}</label>
                <input type="search" name="q" id="flt_q" class="form-control" value="{{ request('q') }}" placeholder="{{ __('Buscar projeto') }}">
            </div>
            <div class="col-md-2">
                <label class="form-label visually-hidden" for="flt_status">{{ __('Status') }}</label>
                <select name="status" id="flt_status" class="form-select">
                    <option value="">{{ __('Todos') }}</option>
                    @foreach(\App\Enums\Accounts\Cronogramas\CronogramaProjectStatus::cases() as $st)
                        @if($viewTab === 'table' && $st->value === 'archived')
                            @continue
                        @endif
                        @if($viewTab === 'archived' && $st->value !== 'archived')
                            @continue
                        @endif
                        <option value="{{ $st->value }}" @selected(request('status') === $st->value)>{{ $st->label() }}</option>
                    @endforeach
                </select>
            </div>
            <div class="col-md-2">
                <input type="date" name="date_from" class="form-control" value="{{ request('date_from') }}" aria-label="{{ __('Data início (de)') }}">
            </div>
            <div class="col-md-2">
                <input type="date" name="date_to" class="form-control" value="{{ request('date_to') }}" aria-label="{{ __('Data fim (até)') }}">
            </div>
            <div class="col-md-2">
                <select name="sort" class="form-select" aria-label="{{ __('Ordenar') }}">
                    <option value="updated_at" @selected(request('sort', 'updated_at') === 'updated_at')>{{ __('Última atualização') }}</option>
                    <option value="name" @selected(request('sort') === 'name')>{{ __('Nome') }}</option>
                    <option value="completion_percent" @selected(request('sort') === 'completion_percent')>{{ __('Progresso') }}</option>
                    <option value="start_date" @selected(request('sort') === 'start_date')>{{ __('Data início') }}</option>
                </select>
            </div>
            <div class="col-md-1 d-flex align-items-end gap-2">
                <button type="submit" class="btn btn-primary">{{ __('Filtrar') }}</button>
                <a class="btn btn-outline-secondary" href="{{ route('admin.cronogramas.dashboard', ['tab' => $viewTab]) }}">{{ __('Limpar') }}</a>
            </div>
        </form>

        @if($viewTab === 'table')
            <div class="table-responsive">
                <table class="table table-sm table-hover align-middle cr-table">
                    <thead>
                        <tr>
                            <th scope="col">{{ __('Projeto') }}</th>
                            <th scope="col">{{ __('Status') }}</th>
                            <th scope="col">{{ __('Progresso') }}</th>
                            <th scope="col">{{ __('Início') }}</th>
                            <th scope="col">{{ __('Término previsto') }}</th>
                            <th scope="col">{{ __('Atividades') }}</th>
                            <th scope="col" class="cr-table-actions">{{ __('Ações') }}</th>
                        </tr>
                    </thead>
                    <tbody>
                        @forelse($projects as $proj)
                            <tr>
                                <td>
                                    <a href="{{ route('admin.cronogramas.projetos.show', array_merge(['project' => $proj->id], $listQuery)) }}">
                                        {{ $proj->name }}
                                    </a>
                                </td>
                                <td>
                                    <span class="badge bg-secondary">{{ \App\Enums\Accounts\Cronogramas\CronogramaProjectStatus::tryFrom($proj->status)?->label() }}</span>
                                </td>
                                <td>
                                    <div class="progress cr-table-progress">
                                        <div class="progress-bar cr-progress-bar-dynamic" role="progressbar" style="--cr-w: {{ $proj->completion_percent }}%" aria-valuenow="{{ $proj->completion_percent }}" aria-valuemin="0" aria-valuemax="100"></div>
                                    </div>
                                    <small class="text-muted d-block">{{ $proj->completion_percent }}%</small>
                                </td>
                                <td>{{ $proj->start_date?->format('d/m/Y') ?? '-' }}</td>
                                <td>{{ $proj->planned_end_date?->format('d/m/Y') ?? '-' }}</td>
                                <td>{{ $proj->activities_count }}</td>
                                <td class="cr-table-actions text-nowrap">
                                    <div class="cr-table-actions-inner">
                                        <a class="btn btn-sm btn-outline-primary" href="{{ route('admin.cronogramas.projetos.show', array_merge(['project' => $proj->id], $listQuery)) }}" title="{{ __('Abrir') }}">
                                            <i class="fa-solid fa-folder-open"></i>
                                        </a>
                                        @if($viewTab === 'table' && $proj->status !== 'archived')
                                            <a class="btn btn-sm btn-outline-info"
                                               href="{{ route('admin.cronogramas.projetos.public.open', array_merge(['project' => $proj->id], $listQuery)) }}"
                                               target="_blank"
                                               rel="noopener"
                                               title="{{ __('Visualização Pública') }}">
                                                <i class="fa-solid fa-eye" aria-hidden="true"></i>
                                                <span class="visually-hidden">{{ __('Visualização Pública') }}</span>
                                            </a>
                                        @endif
                                        @if($canEdit && !in_array($proj->status, ['archived', 'closed']))
                                            <a class="btn btn-sm btn-outline-secondary" href="{{ route('admin.cronogramas.projetos.edit', array_merge(['project' => $proj->id], $listQuery)) }}" title="{{ __('Editar') }}">
                                                <i class="fa-solid fa-pen"></i>
                                            </a>
                                            <form method="post"
                                                  action="{{ route('admin.cronogramas.projetos.arquivar', $proj) }}"
                                                  class="d-inline cr-form-archive-project">
                                                @csrf
                                                @include('components.cronogramas.persist-query', ['params' => $listQuery])
                                                <button type="submit" class="btn btn-sm btn-outline-warning" title="{{ __('Arquivar') }}">
                                                    <i class="fa-solid fa-box-archive"></i>
                                                </button>
                                            </form>
                                        @endif
                                    </div>
                                </td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="7" class="text-center text-muted py-4">{{ __('Nenhum projeto encontrado.') }}</td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>

            <div class="d-flex justify-content-center mt-3">
                {{ $projects->links() }}
            </div>
        @else
            <p class="small text-muted">{{ __('Projetos arquivados podem ser restaurados ou excluídos permanentemente.') }}</p>

            @if(empty($archivedRows))
                <div class="text-center text-muted py-5 border rounded">
                    <i class="fa-solid fa-box-archive fa-2x mb-2 d-block"></i>
                    {{ __('Nenhum projeto arquivado.') }}
                </div>
            @else
                @if($canDelete)
                    <div class="d-flex flex-wrap align-items-center gap-2 mb-3">
                        <button type="button"
                                class="btn btn-sm btn-outline-danger"
                                id="cr-btn-bulk-delete-archived-projects"
                                disabled>
                            <i class="fa-solid fa-trash" aria-hidden="true"></i>
                            {{ __('Excluir selecionados') }}
                            <span class="badge bg-danger ms-1 d-none" id="cr-archived-projects-selected-count">0</span>
                        </button>
                        <small class="text-muted" id="cr-archived-projects-selection-hint" aria-live="polite"></small>
                    </div>
                @endif
                <div class="table-responsive">
                    <table class="table table-sm table-hover align-middle cr-table" id="cr-archived-projects-table">
                        <thead class="table-light">
                            <tr>
                                @if($canDelete)
                                    <th scope="col" class="cr-table-check-col">
                                        <input type="checkbox"
                                               class="form-check-input"
                                               id="cr-archived-projects-select-all"
                                               title="{{ __('Selecionar todos desta página') }}"
                                               aria-label="{{ __('Selecionar todos desta página') }}">
                                    </th>
                                @endif
                                <th scope="col">{{ __('Projeto') }}</th>
                                <th scope="col">{{ __('Status') }}</th>
                                <th scope="col">{{ __('Progresso') }}</th>
                                <th scope="col">{{ __('Início') }}</th>
                                <th scope="col">{{ __('Término previsto') }}</th>
                                <th scope="col">{{ __('Atividades') }}</th>
                                <th scope="col">{{ __('Arquivado em') }}</th>
                                <th scope="col" class="cr-table-actions">{{ __('Ações') }}</th>
                            </tr>
                        </thead>
                        <tbody id="cr-archived-projects-tbody">
                            @foreach($archivedRows as $row)
                                <tr data-project-id="{{ $row['id'] }}">
                                    @if($canDelete)
                                        <td>
                                            <input type="checkbox"
                                                   class="form-check-input cr-archived-project-check"
                                                   value="{{ $row['id'] }}"
                                                   aria-label="{{ __('Selecionar projeto :name', ['name' => $row['name']]) }}">
                                        </td>
                                    @endif
                                    <td>{{ $row['name'] }}</td>
                                    <td><span class="badge bg-secondary">{{ $row['status_label'] }}</span></td>
                                    <td>
                                        <div class="progress cr-table-progress">
                                            <div class="progress-bar cr-progress-bar-dynamic" role="progressbar" style="--cr-w: {{ $row['completion_percent'] }}%" aria-valuenow="{{ $row['completion_percent'] }}" aria-valuemin="0" aria-valuemax="100"></div>
                                        </div>
                                        <small class="text-muted d-block">{{ $row['completion_percent'] }}%</small>
                                    </td>
                                    <td>{{ $row['start_date'] ?? '-' }}</td>
                                    <td>{{ $row['planned_end_date'] ?? '-' }}</td>
                                    <td>{{ $row['activities_count'] }}</td>
                                    <td class="small text-nowrap text-muted">{{ $row['archived_at'] ?? '-' }}</td>
                                    <td class="cr-table-actions text-nowrap">
                                        <div class="cr-table-actions-inner">
                                            <a class="btn btn-sm btn-outline-primary"
                                               href="{{ route('admin.cronogramas.projetos.show', array_merge(['project' => $row['id']], $listQuery)) }}"
                                               title="{{ __('Abrir') }}">
                                                <i class="fa-solid fa-folder-open"></i>
                                            </a>
                                            @if($canEdit)
                                                <form method="post"
                                                      action="{{ route('admin.cronogramas.projetos.desarquivar', $row['id']) }}"
                                                      class="d-inline">
                                                    @csrf
                                                    @include('components.cronogramas.persist-query', ['params' => array_merge($listQuery, ['tab' => 'archived'])])
                                                    <button type="submit" class="btn btn-sm btn-outline-success" title="{{ __('Desarquivar') }}">
                                                        <i class="fa-solid fa-box-open"></i>
                                                    </button>
                                                </form>
                                            @endif
                                            @if($canDelete)
                                                <button type="button"
                                                        class="btn btn-sm btn-outline-danger cr-btn-delete-archived-project"
                                                        data-project-id="{{ $row['id'] }}"
                                                        data-url="{{ route('admin.cronogramas.projetos.destroy', $row['id']) }}"
                                                        title="{{ __('Excluir permanentemente') }}">
                                                    <i class="fa-solid fa-trash"></i>
                                                </button>
                                            @endif
                                        </div>
                                    </td>
                                </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
                @if($projects->total() > 0)
                    <div class="d-flex flex-wrap justify-content-between align-items-center gap-2 mt-3">
                        <small class="text-muted">
                            {{ __('Mostrando :from-:to de :total projeto(s) arquivado(s)', [
                                'from' => $projects->firstItem(),
                                'to' => $projects->lastItem(),
                                'total' => $projects->total(),
                            ]) }}
                        </small>
                        @if($projects->hasPages())
                            <div class="cr-pagination">{{ $projects->links() }}</div>
                        @endif
                    </div>
                @endif
            @endif
        @endif
    </div>
</div>

@endsection

@push('after-scripts')
    <script src="{{ asset('pmar/js/cronogramas-dashboard.js') }}?v={{ filemtime(public_path('pmar/js/cronogramas-dashboard.js')) }}"></script>
@endpush
