@extends('layouts.app')
@section('title', 'Reporte Consolidado')
@section('content')
<div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
    <h4 class="mb-0"><i class="bi bi-bar-chart-line me-1"></i> Reporte Consolidado</h4>
    <div class="d-flex gap-2 align-items-center no-print">
        <form method="GET" class="d-flex gap-2">
            <select name="periodo_id" class="form-select form-select-sm" style="width:220px" onchange="this.form.submit()">
                <option value="">-- Período --</option>
                @foreach($periodos as $p)
                <option value="{{ $p->id }}" {{ optional($periodo)->id == $p->id ? 'selected' : '' }}>
                    {{ $p->nombre_completo }}
                </option>
                @endforeach
            </select>
        </form>
        @if($periodo)
        <a href="{{ route('reportes.csv.consolidado', ['periodo_id' => $periodo->id]) }}"
           class="btn btn-sm btn-outline-success">
            <i class="bi bi-filetype-csv me-1"></i> CSV
        </a>
        <div class="dropdown">
            <button class="btn btn-sm btn-outline-primary dropdown-toggle" data-bs-toggle="dropdown">
                <i class="bi bi-file-earmark-pdf me-1"></i> Reportes PDF
            </button>
            <ul class="dropdown-menu dropdown-menu-end">
                <li><a class="dropdown-item" href="{{ route('reportes.pdf.consolidado-empleado', ['periodo_id'=>$periodo->id]) }}" target="_blank">
                    <i class="bi bi-person-lines-fill me-1"></i> Consolidado por Empleado
                </a></li>
                <li><a class="dropdown-item" href="{{ route('reportes.pdf.horas-adicionales', ['periodo_id'=>$periodo->id]) }}" target="_blank">
                    <i class="bi bi-clock-history me-1"></i> Horas Adicionales
                </a></li>
                <li><a class="dropdown-item" href="{{ route('reportes.pdf.festivos', ['periodo_id'=>$periodo->id]) }}" target="_blank">
                    <i class="bi bi-calendar-x me-1"></i> Domingos y Festivos
                </a></li>
                <li><a class="dropdown-item" href="{{ route('reportes.pdf.compensatorios', ['periodo_id'=>$periodo->id]) }}" target="_blank">
                    <i class="bi bi-arrow-left-right me-1"></i> Compensatorios Tomados
                </a></li>
            </ul>
        </div>
        @endif
        <button onclick="window.print()" class="btn btn-sm btn-outline-secondary">
            <i class="bi bi-printer me-1"></i> Imprimir
        </button>
    </div>
</div>

@if($periodo)
<div class="alert alert-light border">
    <strong>Período:</strong> {{ $periodo->nombre_completo }}
    &nbsp;|&nbsp; {{ $periodo->fecha_inicio->format('d/m/Y') }} al {{ $periodo->fecha_fin->format('d/m/Y') }}
</div>
@endif

@if($datos->count())
<div class="card">
    <div class="card-body p-0 overflow-auto">
        <table class="table table-sm table-bordered mb-0">
            <thead class="table-dark">
                <tr>
                    <th>Empleado</th>
                    <th>Cédula</th>
                    <th class="text-center">Total<br>Horas</th>
                    <th class="text-center">Horas<br>Equivalentes</th>
                    <th class="text-center">Horas<br>Exentas</th>
                    <th class="text-center">Horas<br>Dom/Festivos</th>
                    <th class="text-center">Estado</th>
                </tr>
            </thead>
            <tbody>
                @foreach($datos as $i => $fila)
                @php $hasDist = $fila['distribucion']->count() > 0; @endphp
                <tr class="{{ $hasDist ? 'cursor-pointer' : '' }}"
                    @if($hasDist) data-bs-toggle="collapse" data-bs-target="#cc-{{ $i }}" style="cursor:pointer" @endif>
                    <td>
                        @if($hasDist)
                        <i class="bi bi-chevron-right text-muted me-1" style="font-size:.7rem;transition:.2s" id="chev-{{ $i }}"></i>
                        @endif
                        {{ $fila['empleado']->nombre }}
                    </td>
                    <td>{{ $fila['empleado']->cedula }}</td>
                    <td class="text-center fw-bold">{{ number_format($fila['total_horas'],1) }}</td>
                    <td class="text-center">{{ number_format($fila['horas_productivas'],1) }}</td>
                    <td class="text-center text-info">{{ number_format($fila['horas_exentas'],1) }}</td>
                    <td class="text-center text-success">{{ number_format($fila['horas_festivos'] ?? 0,1) }}</td>
                    <td class="text-center">
                        <span class="badge {{ ['borrador'=>'bg-secondary','enviado'=>'bg-warning text-dark','aprobado'=>'bg-success'][$fila['hoja']->estado] }}">
                            {{ strtoupper($fila['hoja']->estado) }}
                        </span>
                    </td>
                </tr>
                @if($hasDist)
                <tr class="collapse" id="cc-{{ $i }}">
                    <td colspan="9" class="p-0 bg-light">
                        <table class="table table-sm mb-0" style="font-size:.8rem">
                            <thead>
                                <tr class="table-light">
                                    <th style="padding-left:2rem">Centro de Costo</th>
                                    <th class="text-end">Horas</th>
                                    <th class="text-end">%</th>
                                    <th class="text-end">Equivalente (h)</th>
                                    <th colspan="5"></th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($fila['distribucion'] as $dist)
                                <tr>
                                    <td style="padding-left:2rem">
                                        <i class="bi bi-arrow-return-right text-muted me-1"></i>
                                        {{ $dist['nombre'] }}
                                    </td>
                                    <td class="text-end">{{ number_format($dist['horas'],1) }}</td>
                                    <td class="text-end">{{ number_format($dist['porcentaje'],1) }}%</td>
                                    <td class="text-end">{{ number_format($dist['equivalente_horas'] ?? $dist['horas'],1) }} h</td>
                                    <td colspan="5"></td>
                                </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </td>
                </tr>
                @endif
                @endforeach
            </tbody>
            <tfoot class="table-light fw-bold">
                <tr>
                    <td colspan="2">TOTALES</td>
                    <td class="text-center">{{ number_format($datos->sum('total_horas'),1) }}</td>
                    <td class="text-center">{{ number_format($datos->sum('horas_productivas'),1) }}</td>
                    <td class="text-center">{{ number_format($datos->sum('horas_exentas'),1) }}</td>
                    <td colspan="4"></td>
                </tr>
            </tfoot>
        </table>
    </div>
</div>



@elseif($periodo)
<div class="alert alert-info">No hay hojas de tiempo registradas para este período.</div>
@else
<div class="alert alert-warning">Seleccione un período para ver el consolidado.</div>
@endif

@push('scripts')
<script>
document.querySelectorAll('[data-bs-toggle="collapse"]').forEach(function(row) {
    row.addEventListener('click', function() {
        var target = this.getAttribute('data-bs-target');
        var idx = target.replace('#cc-','');
        var chev = document.getElementById('chev-' + idx);
        if (chev) chev.style.transform = document.querySelector(target).classList.contains('show') ? '' : 'rotate(90deg)';
    });
});
</script>
@endpush
@endsection
