@extends('layouts.app')

@section('title', 'Reportes | Veltrix v2')
@section('page_title', 'Reportes')
@section('page_subtitle', 'Gestion operativa en tiempo real')
@section('page_icon', 'bx bxs-report')

@section('content')
    @php
        $currentFilters = is_array($filters ?? null) ? $filters : [];
        $cashierRows = collect($cashiers ?? []);
        $branchRows = collect($branches ?? []);
        $summaryRow = is_array($summary ?? null) ? $summary : [];
        $salesByCashierRows = collect($salesByCashier ?? []);
        $topProductsRows = collect($topProducts ?? []);
        $frequentCustomersRows = collect($frequentCustomers ?? []);
        $inventorySummaryRow = is_array($inventorySummary ?? null) ? $inventorySummary : [];
        $inventorySnapshotRows = collect($inventorySnapshot ?? []);
        $inventoryMovementsRows = collect($inventoryMovements ?? []);
        $kardexRows = collect($kardexByRange ?? []);
        $cashClosingsRows = collect($cashClosings ?? []);
        $receivablesRow = is_array($receivables ?? null) ? $receivables : [];
        $payablesRow = is_array($payables ?? null) ? $payables : [];
        $profitByBranchRows = collect($profitByBranch ?? []);
        $salesByPaymentMethodRows = collect($salesByPaymentMethod ?? []);
    @endphp

    <div class="container-fluid px-4 py-4">
        <div class="card border-0 shadow-sm mb-3">
            <div class="card-body">
                <h1 class="h6 mb-3">Filtros de reporte</h1>
                <form method="GET" action="{{ route('reportes.index') }}" class="row g-2">
                    <div class="col-md-2">
                        <label class="form-label" for="reportDateFrom">Fecha desde</label>
                        <input id="reportDateFrom" type="date" class="form-control" name="fecha_desde" value="{{ (string) ($currentFilters['fecha_desde'] ?? '') }}">
                    </div>
                    <div class="col-md-2">
                        <label class="form-label" for="reportDateTo">Fecha hasta</label>
                        <input id="reportDateTo" type="date" class="form-control" name="fecha_hasta" value="{{ (string) ($currentFilters['fecha_hasta'] ?? '') }}">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label" for="reportCashier">Cajero</label>
                        <select id="reportCashier" class="form-select" name="usuario_id">
                            <option value="0">Todos</option>
                            @foreach ($cashierRows as $cashier)
                                @php
                                    $cashierId = (int) ($cashier['id'] ?? 0);
                                @endphp
                                <option value="{{ $cashierId }}" @selected((int) ($currentFilters['usuario_id'] ?? 0) === $cashierId)>
                                    {{ (string) ($cashier['nombre'] ?? '') }}
                                </option>
                            @endforeach
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label" for="reportBranch">Sucursal</label>
                        <select id="reportBranch" class="form-select" name="sucursal_id">
                            <option value="0">Todas</option>
                            @foreach ($branchRows as $branch)
                                @php
                                    $branchId = (int) ($branch['id'] ?? 0);
                                @endphp
                                <option value="{{ $branchId }}" @selected((int) ($currentFilters['sucursal_id'] ?? 0) === $branchId)>
                                    {{ (string) ($branch['nombre'] ?? '') }}
                                </option>
                            @endforeach
                        </select>
                    </div>
                    <div class="col-md-2 d-flex align-items-end gap-2">
                        <button class="btn btn-primary" type="submit">Aplicar</button>
                        <a class="btn btn-light" href="{{ route('reportes.index') }}">Limpiar</a>
                    </div>
                </form>
            </div>
        </div>

        <div class="row g-3 mb-3">
            <div class="col-md-3">
                <div class="card metric-card border-0 shadow-sm">
                    <div class="card-body">
                        <span class="metric-label">Ventas</span>
                        <h2 class="h5 mb-0">{{ money((float) ($summaryRow['ventas_total'] ?? 0)) }}</h2>
                        <small class="text-muted">{{ (int) ($summaryRow['ventas_count'] ?? 0) }} transacciones</small>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card metric-card border-0 shadow-sm">
                    <div class="card-body">
                        <span class="metric-label">Ticket promedio</span>
                        <h2 class="h5 mb-0">{{ money((float) ($summaryRow['ticket_promedio'] ?? 0)) }}</h2>
                        <small class="text-muted">Promedio por venta</small>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card metric-card border-0 shadow-sm">
                    <div class="card-body">
                        <span class="metric-label">Utilidad estimada</span>
                        <h2 class="h5 mb-0 text-success">{{ money((float) ($summaryRow['utilidad_estimada'] ?? 0)) }}</h2>
                        <small class="text-muted">Venta menos costo compra</small>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card metric-card border-0 shadow-sm">
                    <div class="card-body">
                        <span class="metric-label">Valor inventario</span>
                        <h2 class="h5 mb-0">{{ money((float) ($inventorySummaryRow['valor_inventario'] ?? 0)) }}</h2>
                        <small class="text-muted">Stock bajo: {{ (int) ($inventorySummaryRow['stock_bajo'] ?? 0) }}</small>
                    </div>
                </div>
            </div>
        </div>

        <div class="row g-3 mb-3">
            <div class="col-md-6">
                <div class="card border-0 shadow-sm h-100">
                    <div class="card-body">
                        <h2 class="h6">Cuentas por cobrar</h2>
                        <p class="mb-1">Total credito: <strong>{{ money((float) ($receivablesRow['total_credito'] ?? 0)) }}</strong></p>
                        <p class="mb-1">Total abonado: <strong class="text-success">{{ money((float) ($receivablesRow['total_abonado'] ?? 0)) }}</strong></p>
                        <p class="mb-0">Saldo pendiente: <strong class="text-danger">{{ money((float) ($receivablesRow['total_saldo'] ?? 0)) }}</strong></p>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="card border-0 shadow-sm h-100">
                    <div class="card-body">
                        <h2 class="h6">Cuentas por pagar</h2>
                        <p class="mb-1">Total compras: <strong>{{ money((float) ($payablesRow['total_compras'] ?? 0)) }}</strong></p>
                        <p class="mb-1">Total pagado: <strong class="text-success">{{ money((float) ($payablesRow['total_pagado'] ?? 0)) }}</strong></p>
                        <p class="mb-0">Saldo pendiente: <strong class="text-danger">{{ money((float) ($payablesRow['total_saldo'] ?? 0)) }}</strong></p>
                    </div>
                </div>
            </div>
        </div>

        <div class="row g-3 mb-3">
            <div class="col-lg-6">
                <div class="card border-0 shadow-sm h-100">
                    <div class="card-body">
                        <h2 class="h6 mb-3">Utilidad por sucursal</h2>
                        <div class="table-responsive">
                            <table class="table table-striped table-hover align-middle mb-0">
                                <thead>
                                <tr>
                                    <th>Sucursal</th>
                                    <th>Ventas</th>
                                    <th>Costo</th>
                                    <th>Utilidad</th>
                                </tr>
                                </thead>
                                <tbody>
                                @forelse ($profitByBranchRows as $row)
                                    @php $profit = (float) ($row['utilidad_total'] ?? 0); @endphp
                                    <tr>
                                        <td>{{ (string) ($row['sucursal'] ?? 'Sin sucursal') }}</td>
                                        <td>{{ money((float) ($row['ventas_total'] ?? 0)) }}</td>
                                        <td>{{ money((float) ($row['costo_total'] ?? 0)) }}</td>
                                        <td class="{{ $profit >= 0 ? 'text-success' : 'text-danger' }}">{{ money($profit) }}</td>
                                    </tr>
                                @empty
                                    <tr>
                                        <td colspan="4" class="text-center text-muted py-3">Sin datos para el filtro actual.</td>
                                    </tr>
                                @endforelse
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-lg-6">
                <div class="card border-0 shadow-sm h-100">
                    <div class="card-body">
                        <h2 class="h6 mb-3">Ventas por método de pago</h2>
                        <div class="table-responsive">
                            <table class="table table-striped table-hover align-middle mb-0">
                                <thead>
                                <tr>
                                    <th>Metodo</th>
                                    <th>Pagos</th>
                                    <th>Ventas</th>
                                    <th>Total</th>
                                </tr>
                                </thead>
                                <tbody>
                                @forelse ($salesByPaymentMethodRows as $row)
                                    <tr>
                                        <td>{{ (string) ($row['metodo_pago'] ?? 'n/a') }}</td>
                                        <td>{{ (int) ($row['pagos_count'] ?? 0) }}</td>
                                        <td>{{ (int) ($row['ventas_count'] ?? 0) }}</td>
                                        <td>{{ money((float) ($row['monto_total'] ?? 0)) }}</td>
                                    </tr>
                                @empty
                                    <tr>
                                        <td colspan="4" class="text-center text-muted py-3">Sin pagos para el filtro actual.</td>
                                    </tr>
                                @endforelse
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row g-3 mb-3">
            <div class="col-lg-6">
                <div class="card border-0 shadow-sm h-100">
                    <div class="card-body">
                        <h2 class="h6 mb-3">Ventas por cajero</h2>
                        <div class="table-responsive">
                            <table class="table table-striped table-hover align-middle mb-0">
                                <thead>
                                <tr>
                                    <th>Cajero</th>
                                    <th>Ventas</th>
                                    <th>Total</th>
                                </tr>
                                </thead>
                                <tbody>
                                @forelse ($salesByCashierRows as $row)
                                    <tr>
                                        <td>{{ (string) ($row['nombre'] ?? '') }}</td>
                                        <td>{{ (int) ($row['ventas_count'] ?? 0) }}</td>
                                        <td>{{ money((float) ($row['ventas_total'] ?? 0)) }}</td>
                                    </tr>
                                @empty
                                    <tr>
                                        <td colspan="3" class="text-center text-muted py-3">Sin datos para el filtro actual.</td>
                                    </tr>
                                @endforelse
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-lg-6">
                <div class="card border-0 shadow-sm h-100">
                    <div class="card-body">
                        <h2 class="h6 mb-3">Top productos vendidos</h2>
                        <div class="table-responsive">
                            <table class="table table-striped table-hover align-middle mb-0">
                                <thead>
                                <tr>
                                    <th>Producto</th>
                                    <th>Cantidad</th>
                                    <th>Vendido</th>
                                    <th>Utilidad</th>
                                </tr>
                                </thead>
                                <tbody>
                                @forelse ($topProductsRows as $row)
                                    <tr>
                                        <td>{{ (string) ($row['nombre'] ?? '') }}</td>
                                        <td>{{ number_format((float) ($row['cantidad'] ?? 0), 2, '.', '') }}</td>
                                        <td>{{ money((float) ($row['total_vendido'] ?? 0)) }}</td>
                                        <td>{{ money((float) ($row['utilidad_estimada'] ?? 0)) }}</td>
                                    </tr>
                                @empty
                                    <tr>
                                        <td colspan="4" class="text-center text-muted py-3">Sin datos para el filtro actual.</td>
                                    </tr>
                                @endforelse
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row g-3 mb-3">
            <div class="col-lg-6">
                <div class="card border-0 shadow-sm h-100">
                    <div class="card-body">
                        <h2 class="h6 mb-3">Clientes frecuentes</h2>
                        <div class="table-responsive">
                            <table class="table table-striped table-hover align-middle mb-0">
                                <thead>
                                <tr>
                                    <th>Cliente</th>
                                    <th>Compras</th>
                                    <th>Total</th>
                                    <th>Ultima compra</th>
                                </tr>
                                </thead>
                                <tbody>
                                @forelse ($frequentCustomersRows as $row)
                                    <tr>
                                        <td>{{ (string) ($row['nombre'] ?? '') }}</td>
                                        <td>{{ (int) ($row['compras'] ?? 0) }}</td>
                                        <td>{{ money((float) ($row['monto_total'] ?? 0)) }}</td>
                                        <td>{{ (string) ($row['ultima_compra'] ?? '') }}</td>
                                    </tr>
                                @empty
                                    <tr>
                                        <td colspan="4" class="text-center text-muted py-3">Sin datos para el filtro actual.</td>
                                    </tr>
                                @endforelse
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-lg-6">
                <div class="card border-0 shadow-sm h-100">
                    <div class="card-body">
                        <h2 class="h6 mb-3">Cierres de caja</h2>
                        <div class="table-responsive">
                            <table class="table table-striped table-hover align-middle mb-0">
                                <thead>
                                <tr>
                                    <th>Fecha</th>
                                    <th>Cajero</th>
                                    <th>Caja</th>
                                    <th>Diferencia</th>
                                </tr>
                                </thead>
                                <tbody>
                                @forelse ($cashClosingsRows as $row)
                                    @php
                                        $difference = (float) ($row['diferencia'] ?? 0);
                                        $branchName = trim((string) ($row['sucursal'] ?? ''));
                                        $cashRegister = trim((string) ($row['caja'] ?? ''));
                                        $cashDisplay = trim(($branchName !== '' ? $branchName.' / ' : '').$cashRegister);
                                    @endphp
                                    <tr>
                                        <td>{{ (string) ($row['created_at'] ?? '') }}</td>
                                        <td>{{ (string) ($row['cajero'] ?? '') }}</td>
                                        <td>{{ $cashDisplay !== '' ? $cashDisplay : 'N/A' }}</td>
                                        <td class="{{ $difference === 0.0 ? '' : ($difference > 0 ? 'text-success' : 'text-danger') }}">
                                            {{ money($difference) }}
                                        </td>
                                    </tr>
                                @empty
                                    <tr>
                                        <td colspan="4" class="text-center text-muted py-3">Sin cierres para el filtro actual.</td>
                                    </tr>
                                @endforelse
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row g-3 mb-3">
            <div class="col-lg-6">
                <div class="card border-0 shadow-sm h-100">
                    <div class="card-body">
                        <h2 class="h6 mb-3">Inventario actual</h2>
                        <div class="table-responsive">
                            <table class="table table-striped table-hover align-middle mb-0">
                                <thead>
                                <tr>
                                    <th>Producto</th>
                                    <th>Stock</th>
                                    <th>Minimo</th>
                                    <th>Valor</th>
                                </tr>
                                </thead>
                                <tbody>
                                @forelse ($inventorySnapshotRows as $row)
                                    @php
                                        $stockActual = (float) ($row['stock_actual'] ?? 0);
                                        $stockMinimo = (float) ($row['stock_minimo'] ?? 0);
                                    @endphp
                                    <tr>
                                        <td>{{ (string) ($row['nombre'] ?? '') }}</td>
                                        <td class="{{ $stockActual <= $stockMinimo ? 'text-danger fw-semibold' : '' }}">
                                            {{ number_format($stockActual, 2, '.', '') }}
                                        </td>
                                        <td>{{ number_format($stockMinimo, 2, '.', '') }}</td>
                                        <td>{{ money((float) ($row['valor_inventario'] ?? 0)) }}</td>
                                    </tr>
                                @empty
                                    <tr>
                                        <td colspan="4" class="text-center text-muted py-3">Sin productos disponibles.</td>
                                    </tr>
                                @endforelse
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-lg-6">
                <div class="card border-0 shadow-sm h-100">
                    <div class="card-body">
                        <h2 class="h6 mb-3">Kardex por rango</h2>
                        <div class="table-responsive">
                            <table class="table table-striped table-hover align-middle mb-0">
                                <thead>
                                <tr>
                                    <th>Producto</th>
                                    <th>Entradas</th>
                                    <th>Salidas</th>
                                    <th>Ajustes</th>
                                    <th>Neto</th>
                                </tr>
                                </thead>
                                <tbody>
                                @forelse ($kardexRows as $row)
                                    @php $net = (float) ($row['neto_movimiento'] ?? 0); @endphp
                                    <tr>
                                        <td>{{ (string) ($row['producto'] ?? '') }}</td>
                                        <td>{{ number_format((float) ($row['entradas'] ?? 0), 2, '.', '') }}</td>
                                        <td>{{ number_format((float) ($row['salidas'] ?? 0), 2, '.', '') }}</td>
                                        <td>{{ number_format((float) ($row['ajustes'] ?? 0), 2, '.', '') }}</td>
                                        <td class="{{ $net >= 0 ? 'text-success' : 'text-danger' }}">{{ number_format($net, 2, '.', '') }}</td>
                                    </tr>
                                @empty
                                    <tr>
                                        <td colspan="5" class="text-center text-muted py-3">Sin kardex para el rango actual.</td>
                                    </tr>
                                @endforelse
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <h2 class="h6 mb-3">Movimientos detallados de inventario</h2>
                <div class="table-responsive">
                    <table class="table table-striped table-hover align-middle mb-0">
                        <thead>
                        <tr>
                            <th>Fecha</th>
                            <th>Tipo</th>
                            <th>Producto</th>
                            <th>Cantidad</th>
                            <th>Referencia</th>
                        </tr>
                        </thead>
                        <tbody>
                        @forelse ($inventoryMovementsRows as $row)
                            <tr>
                                <td>{{ (string) ($row['created_at'] ?? '') }}</td>
                                <td>{{ (string) ($row['tipo'] ?? '') }}</td>
                                <td>{{ (string) ($row['producto'] ?? '') }}</td>
                                <td>{{ number_format((float) ($row['cantidad'] ?? 0), 2, '.', '') }}</td>
                                <td>{{ (string) ($row['referencia'] ?? '') }}</td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="5" class="text-center text-muted py-3">Sin movimientos para el filtro actual.</td>
                            </tr>
                        @endforelse
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
@endsection
