<?php
$filters = $filters ?? [
    'fecha_desde' => date('Y-m-d', strtotime('-30 days')),
    'fecha_hasta' => date('Y-m-d'),
    'usuario_id' => 0,
    'sucursal_id' => 0,
];
$cashiers = $cashiers ?? [];
$branches = $branches ?? [];
$summary = $summary ?? [];
$salesByCashier = $salesByCashier ?? [];
$topProducts = $topProducts ?? [];
$frequentCustomers = $frequentCustomers ?? [];
$inventorySummary = $inventorySummary ?? [];
$inventorySnapshot = $inventorySnapshot ?? [];
$inventoryMovements = $inventoryMovements ?? [];
$kardexByRange = $kardexByRange ?? [];
$cashClosings = $cashClosings ?? [];
$receivables = $receivables ?? [];
$payables = $payables ?? [];
$profitByBranch = $profitByBranch ?? [];
$salesByPaymentMethod = $salesByPaymentMethod ?? [];
?>

<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="<?= e(url('reportes')) ?>" class="row g-2">
            <div class="col-md-2">
                <label class="form-label">Fecha desde</label>
                <input type="date" class="form-control" name="fecha_desde" value="<?= e((string) ($filters['fecha_desde'] ?? '')) ?>">
            </div>
            <div class="col-md-2">
                <label class="form-label">Fecha hasta</label>
                <input type="date" class="form-control" name="fecha_hasta" value="<?= e((string) ($filters['fecha_hasta'] ?? '')) ?>">
            </div>
            <div class="col-md-3">
                <label class="form-label">Cajero</label>
                <select class="form-select" name="usuario_id">
                    <option value="0">Todos</option>
                    <?php foreach ($cashiers as $cashier): ?>
                        <option value="<?= e((string) $cashier['id']) ?>" <?= (int) ($filters['usuario_id'] ?? 0) === (int) $cashier['id'] ? 'selected' : '' ?>>
                            <?= e($cashier['nombre']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label">Sucursal</label>
                <select class="form-select" name="sucursal_id">
                    <option value="0">Todas</option>
                    <?php foreach ($branches as $branch): ?>
                        <option value="<?= e((string) $branch['id']) ?>" <?= (int) ($filters['sucursal_id'] ?? 0) === (int) $branch['id'] ? 'selected' : '' ?>>
                            <?= e($branch['nombre']) ?>
                        </option>
                    <?php 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="<?= e(url('reportes')) ?>">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"><?= e(money($summary['ventas_total'] ?? 0)) ?></h2>
                <small class="text-muted"><?= e((string) ($summary['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"><?= e(money($summary['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"><?= e(money($summary['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"><?= e(money($inventorySummary['valor_inventario'] ?? 0)) ?></h2>
                <small class="text-muted">Stock bajo: <?= e((string) ($inventorySummary['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">
            <div class="card-body">
                <h2 class="h6">Cuentas por cobrar</h2>
                <p class="mb-1">Total credito: <strong><?= e(money($receivables['total_credito'] ?? 0)) ?></strong></p>
                <p class="mb-1">Total abonado: <strong class="text-success"><?= e(money($receivables['total_abonado'] ?? 0)) ?></strong></p>
                <p class="mb-0">Saldo pendiente: <strong class="text-danger"><?= e(money($receivables['total_saldo'] ?? 0)) ?></strong></p>
            </div>
        </div>
    </div>
    <div class="col-md-6">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <h2 class="h6">Cuentas por pagar</h2>
                <p class="mb-1">Total compras: <strong><?= e(money($payables['total_compras'] ?? 0)) ?></strong></p>
                <p class="mb-1">Total pagado: <strong class="text-success"><?= e(money($payables['total_pagado'] ?? 0)) ?></strong></p>
                <p class="mb-0">Saldo pendiente: <strong class="text-danger"><?= e(money($payables['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">
                        <thead>
                        <tr>
                            <th>Sucursal</th>
                            <th>Ventas</th>
                            <th>Costo</th>
                            <th>Utilidad</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php if ($profitByBranch === []): ?>
                            <tr><td colspan="4" class="text-center text-muted py-3">Sin datos para el filtro actual.</td></tr>
                        <?php endif; ?>
                        <?php foreach ($profitByBranch as $row): ?>
                            <tr>
                                <td><?= e((string) ($row['sucursal'] ?? 'Sin sucursal')) ?></td>
                                <td><?= e(money((float) ($row['ventas_total'] ?? 0))) ?></td>
                                <td><?= e(money((float) ($row['costo_total'] ?? 0))) ?></td>
                                <td class="<?= (float) ($row['utilidad_total'] ?? 0) >= 0 ? 'text-success' : 'text-danger' ?>">
                                    <?= e(money((float) ($row['utilidad_total'] ?? 0))) ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        </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">
                        <thead>
                        <tr>
                            <th>Método</th>
                            <th>Pagos</th>
                            <th>Ventas</th>
                            <th>Total</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php if ($salesByPaymentMethod === []): ?>
                            <tr><td colspan="4" class="text-center text-muted py-3">Sin pagos para el filtro actual.</td></tr>
                        <?php endif; ?>
                        <?php foreach ($salesByPaymentMethod as $row): ?>
                            <tr>
                                <td><?= e((string) ($row['metodo_pago'] ?? 'n/a')) ?></td>
                                <td><?= e((string) ($row['pagos_count'] ?? 0)) ?></td>
                                <td><?= e((string) ($row['ventas_count'] ?? 0)) ?></td>
                                <td><?= e(money((float) ($row['monto_total'] ?? 0))) ?></td>
                            </tr>
                        <?php endforeach; ?>
                        </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">
                        <thead>
                        <tr>
                            <th>Cajero</th>
                            <th>Ventas</th>
                            <th>Total</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php if ($salesByCashier === []): ?>
                            <tr><td colspan="3" class="text-center text-muted py-3">Sin datos para el filtro actual.</td></tr>
                        <?php endif; ?>
                        <?php foreach ($salesByCashier as $row): ?>
                            <tr>
                                <td><?= e($row['nombre']) ?></td>
                                <td><?= e((string) $row['ventas_count']) ?></td>
                                <td><?= e(money($row['ventas_total'])) ?></td>
                            </tr>
                        <?php endforeach; ?>
                        </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">
                        <thead>
                        <tr>
                            <th>Producto</th>
                            <th>Cantidad</th>
                            <th>Vendido</th>
                            <th>Utilidad</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php if ($topProducts === []): ?>
                            <tr><td colspan="4" class="text-center text-muted py-3">Sin datos para el filtro actual.</td></tr>
                        <?php endif; ?>
                        <?php foreach ($topProducts as $row): ?>
                            <tr>
                                <td><?= e($row['nombre']) ?></td>
                                <td><?= e((string) $row['cantidad']) ?></td>
                                <td><?= e(money($row['total_vendido'])) ?></td>
                                <td><?= e(money($row['utilidad_estimada'])) ?></td>
                            </tr>
                        <?php endforeach; ?>
                        </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">
                        <thead>
                        <tr>
                            <th>Cliente</th>
                            <th>Compras</th>
                            <th>Total</th>
                            <th>Ultima compra</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php if ($frequentCustomers === []): ?>
                            <tr><td colspan="4" class="text-center text-muted py-3">Sin datos para el filtro actual.</td></tr>
                        <?php endif; ?>
                        <?php foreach ($frequentCustomers as $row): ?>
                            <tr>
                                <td><?= e($row['nombre']) ?></td>
                                <td><?= e((string) $row['compras']) ?></td>
                                <td><?= e(money($row['monto_total'])) ?></td>
                                <td><?= e($row['ultima_compra'] ?? '') ?></td>
                            </tr>
                        <?php endforeach; ?>
                        </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">
                        <thead>
                        <tr>
                            <th>Fecha</th>
                            <th>Cajero</th>
                            <th>Caja</th>
                            <th>Diferencia</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php if ($cashClosings === []): ?>
                            <tr><td colspan="4" class="text-center text-muted py-3">Sin cierres para el filtro actual.</td></tr>
                        <?php endif; ?>
                        <?php foreach ($cashClosings as $row): ?>
                            <tr>
                                <td><?= e($row['created_at'] ?? '') ?></td>
                                <td><?= e($row['cajero'] ?? '') ?></td>
                                <td><?= e(($row['sucursal'] ? $row['sucursal'] . ' / ' : '') . ($row['caja'] ?? '')) ?></td>
                                <td class="<?= ((float) ($row['diferencia'] ?? 0)) === 0.0 ? '' : (((float) ($row['diferencia'] ?? 0)) > 0 ? 'text-success' : 'text-danger') ?>">
                                    <?= e(money($row['diferencia'] ?? 0)) ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row g-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">
                        <thead>
                        <tr>
                            <th>Producto</th>
                            <th>Stock</th>
                            <th>Minimo</th>
                            <th>Valor</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php if ($inventorySnapshot === []): ?>
                            <tr><td colspan="4" class="text-center text-muted py-3">Sin productos disponibles.</td></tr>
                        <?php endif; ?>
                        <?php foreach ($inventorySnapshot as $row): ?>
                            <tr>
                                <td><?= e($row['nombre']) ?></td>
                                <td class="<?= (float) $row['stock_actual'] <= (float) $row['stock_minimo'] ? 'text-danger fw-semibold' : '' ?>">
                                    <?= e((string) $row['stock_actual']) ?>
                                </td>
                                <td><?= e((string) $row['stock_minimo']) ?></td>
                                <td><?= e(money($row['valor_inventario'])) ?></td>
                            </tr>
                        <?php endforeach; ?>
                        </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">
                        <thead>
                        <tr>
                            <th>Producto</th>
                            <th>Entradas</th>
                            <th>Salidas</th>
                            <th>Ajustes</th>
                            <th>Neto</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php if ($kardexByRange === []): ?>
                            <tr><td colspan="5" class="text-center text-muted py-3">Sin kardex para el rango actual.</td></tr>
                        <?php endif; ?>
                        <?php foreach ($kardexByRange as $row): ?>
                            <tr>
                                <td><?= e($row['producto'] ?? '') ?></td>
                                <td><?= e((string) ($row['entradas'] ?? 0)) ?></td>
                                <td><?= e((string) ($row['salidas'] ?? 0)) ?></td>
                                <td><?= e((string) ($row['ajustes'] ?? 0)) ?></td>
                                <td class="<?= (float) ($row['neto_movimiento'] ?? 0) >= 0 ? 'text-success' : 'text-danger' ?>">
                                    <?= e((string) ($row['neto_movimiento'] ?? 0)) ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="card border-0 shadow-sm mt-3">
    <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">
                <thead>
                <tr>
                    <th>Fecha</th>
                    <th>Tipo</th>
                    <th>Producto</th>
                    <th>Cantidad</th>
                    <th>Referencia</th>
                </tr>
                </thead>
                <tbody>
                <?php if ($inventoryMovements === []): ?>
                    <tr><td colspan="5" class="text-center text-muted py-3">Sin movimientos para el filtro actual.</td></tr>
                <?php endif; ?>
                <?php foreach ($inventoryMovements as $row): ?>
                    <tr>
                        <td><?= e($row['created_at'] ?? '') ?></td>
                        <td><?= e($row['tipo'] ?? '') ?></td>
                        <td><?= e($row['producto'] ?? '') ?></td>
                        <td><?= e((string) $row['cantidad']) ?></td>
                        <td><?= e((string) ($row['referencia'] ?? '')) ?></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
