<?php
$currentSales = is_array($currentSales ?? null) ? $currentSales : [
    'ventas_count' => 0,
    'ventas_total' => 0,
    'ventas_efectivo' => 0,
    'ventas_otros' => 0,
];
$currentExpected = (float) ($currentExpected ?? 0);
$currentAdjustments = is_array($currentAdjustments ?? null) ? $currentAdjustments : [
    'total_ingresos' => 0,
    'total_egresos' => 0,
    'neto_ajustes' => 0,
    'total_movimientos' => 0,
];
$currentMovements = is_array($currentMovements ?? null) ? $currentMovements : [];
$transferTargets = is_array($transferTargets ?? null) ? $transferTargets : [];
$transferHistory = is_array($transferHistory ?? null) ? $transferHistory : [];
$pendingIncomingTransfers = is_array($pendingIncomingTransfers ?? null) ? $pendingIncomingTransfers : [];
$pendingOutgoingTransfers = is_array($pendingOutgoingTransfers ?? null) ? $pendingOutgoingTransfers : [];
$historySummary = is_array($historySummary ?? null) ? $historySummary : [
    'total_cierres' => 0,
    'total_esperado' => 0,
    'total_contado' => 0,
    'total_diferencia' => 0,
];
$cashBoxes = is_array($cashBoxes ?? null) ? $cashBoxes : [];
$cashiers = is_array($cashiers ?? null) ? $cashiers : [];
$branches = is_array($branches ?? null) ? $branches : [];
$history = is_array($history ?? null) ? $history : [];
$filters = is_array($filters ?? null) ? $filters : [
    'fecha_desde' => '',
    'fecha_hasta' => '',
    'usuario_id' => 0,
    'sucursal_id' => 0,
];
$canViewAllClosings = (bool) ($canViewAllClosings ?? false);
$userBranchId = (int) ($userBranchId ?? 0);
$cashModalOld = trim((string) old('_cash_modal', ''));

$movementType = (string) old('tipo', 'ingreso');
if ($movementType !== 'egreso') {
    $movementType = 'ingreso';
}
$movementAmount = (string) old('monto', '');
$movementConcept = (string) old('concepto', '');
$movementObservation = (string) old('observacion', '');

$transferTargetId = (int) old('apertura_destino_id', 0);
$transferAmount = (string) old('monto', '');
$transferConcept = (string) old('concepto', 'Traspaso entre cajas');
$transferObservation = (string) old('observacion', '');

$closeAmount = (string) old('monto_cierre', '');
$closeNotes = (string) old('notas', '');

$topbar_actions = [
    [
        'type' => 'modal',
        'label' => 'Ingresos / egresos',
        'icon' => 'bx bx-transfer',
        'class' => 'btn btn-outline-secondary btn-sm vx-topbar-action',
        'target_modal' => '#cashMovementModal',
        'disabled' => !$current,
    ],
    [
        'type' => 'modal',
        'label' => 'Traspaso cajas',
        'icon' => 'bx bx-shuffle',
        'class' => 'btn btn-outline-dark btn-sm vx-topbar-action',
        'target_modal' => '#cashTransferModal',
        'disabled' => !$current,
    ],
    [
        'type' => 'modal',
        'label' => 'Arqueo y cierre',
        'icon' => 'bx bx-wallet-alt',
        'class' => 'btn btn-outline-primary btn-sm vx-topbar-action',
        'target_modal' => '#cashCloseModal',
        'disabled' => !$current,
    ],
];
$show_company_switcher = false;
?>

<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">Caja actual</span>
                <h2 class="h6 mb-1"><?= $current ? 'Abierta' : 'Sin apertura' ?></h2>
                <small class="text-muted">
                    <?= $current ? ('Desde ' . e((string) ($current['fecha_apertura'] ?? ''))) : 'Abre caja para operar' ?>
                </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">Efectivo esperado</span>
                <h2 class="h5 mb-0"><?= e(money($currentExpected)) ?></h2>
            </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">Ventas del turno</span>
                <h2 class="h5 mb-0"><?= e(money($currentSales['ventas_total'] ?? 0)) ?></h2>
                <small class="text-muted"><?= e((string) ($currentSales['ventas_count'] ?? 0)) ?> ventas</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">Ajustes manuales</span>
                <h2 class="h5 mb-0 <?= ((float) ($currentAdjustments['neto_ajustes'] ?? 0)) < 0 ? 'text-danger' : (((float) ($currentAdjustments['neto_ajustes'] ?? 0)) > 0 ? 'text-success' : '') ?>">
                    <?= e(money($currentAdjustments['neto_ajustes'] ?? 0)) ?>
                </h2>
                <small class="text-muted">
                    Ing: <?= e(money($currentAdjustments['total_ingresos'] ?? 0)) ?>
                    | Egr: <?= e(money($currentAdjustments['total_egresos'] ?? 0)) ?>
                </small>
            </div>
        </div>
    </div>
</div>

<div class="row g-3">
    <div class="col-lg-4">
        <div class="card border-0 shadow-sm mb-3">
            <div class="card-body">
                <h2 class="h6 mb-3">Apertura de caja</h2>
                <?php if ($current): ?>
                    <p class="text-success mb-1">Caja abierta desde: <?= e((string) ($current['fecha_apertura'] ?? '')) ?></p>
                    <p class="mb-1">Monto apertura: <?= e(money($current['monto_apertura'] ?? 0)) ?></p>
                    <p class="mb-1">Caja: <?= e((string) ($current['caja_nombre'] ?? 'General')) ?></p>
                    <p class="mb-0">Sucursal: <?= e((string) ($current['sucursal_nombre'] ?? 'Sin sucursal')) ?></p>
                <?php else: ?>
                    <?php if ($userBranchId > 0): ?>
                        <div class="alert alert-info py-2">
                            Tu usuario está asignado a sucursal #<?= e((string) $userBranchId) ?>. Debes abrir caja de esa sucursal.
                        </div>
                    <?php endif; ?>
                    <form action="<?= e(url('caja/abrir')) ?>" method="post">
                        <?= csrf_field() ?>
                        <div class="mb-2">
                            <label class="form-label">Caja</label>
                            <select class="form-select" name="caja_id">
                                <?php if ($userBranchId <= 0): ?>
                                    <option value="">Caja general (sin asignar)</option>
                                <?php else: ?>
                                    <option value="">Seleccione una caja...</option>
                                <?php endif; ?>
                                <?php foreach ($cashBoxes as $box): ?>
                                    <option value="<?= e((string) $box['id']) ?>">
                                        <?= e($box['nombre']) ?>
                                        <?= !empty($box['sucursal']) ? (' - ' . e($box['sucursal'])) : '' ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Monto inicial</label>
                            <input type="number" step="0.01" min="0" class="form-control" name="monto_apertura" required>
                        </div>
                        <button class="btn btn-primary w-100" type="submit">Abrir caja</button>
                    </form>
                <?php endif; ?>
            </div>
        </div>

        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <h2 class="h6 mb-3">Operaciones de caja</h2>
                <?php if (!$current): ?>
                    <div class="alert alert-warning mb-3">Abre caja para habilitar las acciones del menú superior.</div>
                <?php endif; ?>
                <hr>
                <div class="small text-muted">
                    <div>Movimientos turno: <?= e((string) ($currentAdjustments['total_movimientos'] ?? 0)) ?></div>
                    <div>Pendientes por aprobar: <?= e((string) count($pendingIncomingTransfers)) ?></div>
                    <div>Pendientes enviados: <?= e((string) count($pendingOutgoingTransfers)) ?></div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-lg-8">
        <div class="card border-0 shadow-sm mb-3">
            <div class="card-body">
                <h1 class="h5 mb-3">Reporte de cierres</h1>
                <form method="get" action="<?= e(url('caja')) ?>" class="row g-2">
                    <div class="col-md-3">
                        <label class="form-label">Desde</label>
                        <input type="date" class="form-control" name="fecha_desde" value="<?= e((string) ($filters['fecha_desde'] ?? '')) ?>">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">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">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-3">
                        <label class="form-label">Cajero</label>
                        <select class="form-select" name="usuario_id" <?= !$canViewAllClosings ? 'disabled' : '' ?>>
                            <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>
                        <?php if (!$canViewAllClosings): ?>
                            <small class="text-muted">Solo puedes ver tus cierres.</small>
                        <?php endif; ?>
                    </div>
                    <div class="col-12 d-flex gap-2">
                        <button class="btn btn-primary" type="submit">Filtrar</button>
                        <a class="btn btn-light" href="<?= e(url('caja')) ?>">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 h-100">
                    <div class="card-body">
                        <span class="metric-label">Cierres</span>
                        <h2 class="h5 mb-0"><?= e((string) ($historySummary['total_cierres'] ?? 0)) ?></h2>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card metric-card border-0 shadow-sm h-100">
                    <div class="card-body">
                        <span class="metric-label">Esperado</span>
                        <h2 class="h6 mb-0"><?= e(money($historySummary['total_esperado'] ?? 0)) ?></h2>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card metric-card border-0 shadow-sm h-100">
                    <div class="card-body">
                        <span class="metric-label">Contado</span>
                        <h2 class="h6 mb-0"><?= e(money($historySummary['total_contado'] ?? 0)) ?></h2>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card metric-card border-0 shadow-sm h-100">
                    <div class="card-body">
                        <span class="metric-label">Diferencia total</span>
                        <h2 class="h6 mb-0 <?= ((float) ($historySummary['total_diferencia'] ?? 0)) < 0 ? 'text-danger' : (((float) ($historySummary['total_diferencia'] ?? 0)) > 0 ? 'text-success' : '') ?>">
                            <?= e(money($historySummary['total_diferencia'] ?? 0)) ?>
                        </h2>
                    </div>
                </div>
            </div>
        </div>

        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <h2 class="h5 mb-3">Historial de cierres por cajero</h2>
                <div class="table-responsive">
                    <table class="table table-striped table-hover table-sm align-middle">
                        <thead>
                        <tr>
                            <th>Fecha cierre</th>
                            <th>Cajero</th>
                            <th>Sucursal</th>
                            <th>Caja</th>
                            <th>Apertura</th>
                            <th>Esperado</th>
                            <th>Contado</th>
                            <th>Diferencia</th>
                            <th>Observación</th>
                            <th>Resumen</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($history as $item): ?>
                            <?php
                            $difference = (float) ($item['diferencia'] ?? 0);
                            $diffClass = $difference > 0.009
                                ? 'text-bg-success'
                                : ($difference < -0.009 ? 'text-bg-danger' : 'text-bg-secondary');
                            ?>
                            <tr>
                                <td><?= e((string) ($item['fecha_cierre'] ?? '')) ?></td>
                                <td><?= e((string) ($item['cajero'] ?? '')) ?></td>
                                <td><?= e((string) ($item['sucursal'] ?? 'Sin sucursal')) ?></td>
                                <td><?= e((string) ($item['caja'] ?? 'General')) ?></td>
                                <td><?= e(money($item['monto_apertura'] ?? 0)) ?></td>
                                <td><?= e(money($item['monto_esperado'] ?? 0)) ?></td>
                                <td><?= e(money($item['monto_real'] ?? 0)) ?></td>
                                <td><span class="badge <?= $diffClass ?>"><?= e(money($difference)) ?></span></td>
                                <td><?= e((string) ($item['notas'] ?? '')) ?></td>
                                <td>
                                    <a
                                        class="btn btn-sm btn-outline-primary"
                                        href="<?= e(url('caja/cierres/' . (int) $item['apertura_id'] . '/imprimir')) ?>"
                                        target="_blank"
                                    >
                                        Imprimir
                                    </a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        <?php if (empty($history)): ?>
                            <tr>
                                <td colspan="10" class="text-center text-muted py-3">No hay cierres para los filtros seleccionados.</td>
                            </tr>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="cashMovementModal" tabindex="-1" aria-labelledby="cashMovementModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-scrollable">
        <div class="modal-content border-0 shadow">
            <div class="modal-header">
                <h2 class="h6 mb-0" id="cashMovementModalLabel">Ingresos y egresos manuales</h2>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
            </div>
            <div class="modal-body">
                <?php if ($current): ?>
                    <form action="<?= e(url('caja/movimientos')) ?>" method="post" class="mb-3">
                        <?= csrf_field() ?>
                        <input type="hidden" name="_cash_modal" value="movement">
                        <div class="mb-2">
                            <label class="form-label">Tipo</label>
                            <select class="form-select" name="tipo" required>
                                <option value="ingreso" <?= $movementType === 'ingreso' ? 'selected' : '' ?>>Ingreso</option>
                                <option value="egreso" <?= $movementType === 'egreso' ? 'selected' : '' ?>>Egreso</option>
                            </select>
                        </div>
                        <div class="mb-2">
                            <label class="form-label">Monto</label>
                            <input type="number" step="0.01" min="0.01" class="form-control" name="monto" value="<?= e($movementAmount) ?>" required>
                        </div>
                        <div class="mb-2">
                            <label class="form-label">Concepto</label>
                            <input class="form-control" name="concepto" maxlength="160" placeholder="Ej: Caja menor, transporte, ajuste efectivo" value="<?= e($movementConcept) ?>" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Observación</label>
                            <textarea class="form-control" name="observacion" rows="2" placeholder="Detalle opcional"><?= e($movementObservation) ?></textarea>
                        </div>
                        <button class="btn btn-outline-secondary w-100" type="submit">Registrar movimiento</button>
                    </form>

                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <small class="text-muted">Movimientos del turno: <?= e((string) ($currentAdjustments['total_movimientos'] ?? 0)) ?></small>
                        <small class="text-muted">Neto: <?= e(money($currentAdjustments['neto_ajustes'] ?? 0)) ?></small>
                    </div>
                    <div class="table-responsive">
                        <table class="table table-sm table-striped mb-0">
                            <thead>
                            <tr>
                                <th>Tipo</th>
                                <th>Concepto</th>
                                <th>Monto</th>
                            </tr>
                            </thead>
                            <tbody>
                            <?php foreach (array_slice($currentMovements, 0, 8) as $movement): ?>
                                <tr>
                                    <td>
                                        <span class="badge <?= ($movement['tipo'] ?? '') === 'ingreso' ? 'text-bg-success' : 'text-bg-danger' ?>">
                                            <?= e((string) ($movement['tipo'] ?? '')) ?>
                                        </span>
                                    </td>
                                    <td><?= e((string) ($movement['concepto'] ?? '')) ?></td>
                                    <td><?= e(money($movement['monto'] ?? 0)) ?></td>
                                </tr>
                            <?php endforeach; ?>
                            <?php if (empty($currentMovements)): ?>
                                <tr>
                                    <td colspan="3" class="text-center text-muted">Sin movimientos manuales.</td>
                                </tr>
                            <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                <?php else: ?>
                    <div class="alert alert-warning mb-0">Abre caja para registrar ingresos y egresos manuales.</div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="cashTransferModal" tabindex="-1" aria-labelledby="cashTransferModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl modal-dialog-scrollable">
        <div class="modal-content border-0 shadow">
            <div class="modal-header">
                <h2 class="h6 mb-0" id="cashTransferModalLabel">Traspaso entre cajas</h2>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
            </div>
            <div class="modal-body">
                <?php if ($current): ?>
                    <?php if (empty($transferTargets)): ?>
                        <div class="alert alert-warning">No hay otra caja abierta para recibir traspaso.</div>
                    <?php else: ?>
                        <form action="<?= e(url('caja/traspasos')) ?>" method="post" class="mb-3">
                            <?= csrf_field() ?>
                            <input type="hidden" name="_cash_modal" value="transfer">
                            <div class="mb-2">
                                <label class="form-label">Caja destino</label>
                                <select class="form-select" name="apertura_destino_id" required>
                                    <option value="">Seleccione...</option>
                                    <?php foreach ($transferTargets as $target): ?>
                                        <option value="<?= e((string) $target['id']) ?>" <?= $transferTargetId === (int) $target['id'] ? 'selected' : '' ?>>
                                            <?= e((string) ($target['caja'] ?? 'General')) ?>
                                            <?= !empty($target['sucursal']) ? (' - ' . e((string) $target['sucursal'])) : '' ?>
                                            <?= ' | Cajero: ' . e((string) ($target['cajero'] ?? '')) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="mb-2">
                                <label class="form-label">Monto</label>
                                <input type="number" step="0.01" min="0.01" class="form-control" name="monto" value="<?= e($transferAmount) ?>" required>
                            </div>
                            <div class="mb-2">
                                <label class="form-label">Concepto</label>
                                <input class="form-control" name="concepto" maxlength="160" value="<?= e($transferConcept) ?>" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Observación</label>
                                <textarea class="form-control" name="observacion" rows="2" placeholder="Detalle opcional"><?= e($transferObservation) ?></textarea>
                            </div>
                            <button class="btn btn-outline-dark w-100" type="submit">Registrar traspaso</button>
                        </form>
                    <?php endif; ?>

                    <h3 class="h6 mb-2">Pendientes por aprobar (recibidos)</h3>
                    <div class="table-responsive">
                        <table class="table table-sm table-striped mb-3">
                            <thead>
                            <tr>
                                <th>Origen</th>
                                <th>Monto</th>
                                <th>Acción</th>
                            </tr>
                            </thead>
                            <tbody>
                            <?php foreach (array_slice($pendingIncomingTransfers, 0, 8) as $transfer): ?>
                                <tr>
                                    <td><?= e((string) ($transfer['caja_origen'] ?? 'General')) ?> | <?= e((string) ($transfer['cajero_origen'] ?? '')) ?></td>
                                    <td><?= e(money($transfer['monto'] ?? 0)) ?></td>
                                    <td>
                                        <form action="<?= e(url('caja/traspasos/' . (int) $transfer['id'] . '/aprobar')) ?>" method="post" class="d-inline-block">
                                            <?= csrf_field() ?>
                                            <button class="btn btn-sm btn-success" type="submit">Aprobar</button>
                                        </form>
                                        <form action="<?= e(url('caja/traspasos/' . (int) $transfer['id'] . '/rechazar')) ?>" method="post" class="d-inline-block ms-1" onsubmit="return confirm('¿Rechazar este traspaso?');">
                                            <?= csrf_field() ?>
                                            <button class="btn btn-sm btn-outline-danger" type="submit">Rechazar</button>
                                        </form>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                            <?php if (empty($pendingIncomingTransfers)): ?>
                                <tr>
                                    <td colspan="3" class="text-center text-muted">No tienes traspasos pendientes por aprobar.</td>
                                </tr>
                            <?php endif; ?>
                            </tbody>
                        </table>
                    </div>

                    <h3 class="h6 mb-2">Pendientes enviados</h3>
                    <div class="table-responsive">
                        <table class="table table-sm table-striped mb-3">
                            <thead>
                            <tr>
                                <th>Destino</th>
                                <th>Monto</th>
                                <th>Estado</th>
                            </tr>
                            </thead>
                            <tbody>
                            <?php foreach (array_slice($pendingOutgoingTransfers, 0, 8) as $transfer): ?>
                                <tr>
                                    <td><?= e((string) ($transfer['caja_destino'] ?? 'General')) ?> | <?= e((string) ($transfer['cajero_destino'] ?? '')) ?></td>
                                    <td><?= e(money($transfer['monto'] ?? 0)) ?></td>
                                    <td><span class="badge text-bg-warning">pendiente</span></td>
                                </tr>
                            <?php endforeach; ?>
                            <?php if (empty($pendingOutgoingTransfers)): ?>
                                <tr>
                                    <td colspan="3" class="text-center text-muted">No tienes traspasos pendientes enviados.</td>
                                </tr>
                            <?php endif; ?>
                            </tbody>
                        </table>
                    </div>

                    <h3 class="h6 mb-2">Historial de traspasos</h3>
                    <div class="table-responsive">
                        <table class="table table-sm table-striped mb-0">
                            <thead>
                            <tr>
                                <th>Tipo</th>
                                <th>Caja contraparte</th>
                                <th>Monto</th>
                                <th>Estado</th>
                            </tr>
                            </thead>
                            <tbody>
                            <?php foreach (array_slice($transferHistory, 0, 10) as $transfer): ?>
                                <?php
                                $isOutgoing = (int) ($transfer['apertura_origen_id'] ?? 0) === (int) ($current['id'] ?? 0);
                                $counterpart = $isOutgoing
                                    ? ((string) ($transfer['caja_destino'] ?? 'General') . ' | ' . (string) ($transfer['cajero_destino'] ?? ''))
                                    : ((string) ($transfer['caja_origen'] ?? 'General') . ' | ' . (string) ($transfer['cajero_origen'] ?? ''));
                                $estado = (string) ($transfer['estado'] ?? 'pendiente');
                                $estadoClass = $estado === 'aprobado'
                                    ? 'text-bg-success'
                                    : ($estado === 'rechazado' ? 'text-bg-danger' : 'text-bg-warning');
                                ?>
                                <tr>
                                    <td>
                                        <span class="badge <?= $isOutgoing ? 'text-bg-danger' : 'text-bg-success' ?>">
                                            <?= $isOutgoing ? 'Salida' : 'Entrada' ?>
                                        </span>
                                    </td>
                                    <td><?= e($counterpart) ?></td>
                                    <td><?= e(money($transfer['monto'] ?? 0)) ?></td>
                                    <td><span class="badge <?= $estadoClass ?>"><?= e($estado) ?></span></td>
                                </tr>
                            <?php endforeach; ?>
                            <?php if (empty($transferHistory)): ?>
                                <tr>
                                    <td colspan="4" class="text-center text-muted">Sin historial de traspasos.</td>
                                </tr>
                            <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                <?php else: ?>
                    <div class="alert alert-warning mb-0">Abre caja para traspasar efectivo a otra caja.</div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="cashCloseModal" tabindex="-1" aria-labelledby="cashCloseModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content border-0 shadow">
            <div class="modal-header">
                <h2 class="h6 mb-0" id="cashCloseModalLabel">Arqueo y cierre</h2>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
            </div>
            <div class="modal-body">
                <?php if ($current): ?>
                    <form action="<?= e(url('caja/cerrar')) ?>" method="post" id="closeCashForm">
                        <?= csrf_field() ?>
                        <input type="hidden" name="_cash_modal" value="close">
                        <div class="mb-2">
                            <label class="form-label">Efectivo esperado</label>
                            <input
                                id="cashExpectedAmount"
                                type="number"
                                step="0.01"
                                class="form-control"
                                value="<?= e(number_format($currentExpected, 2, '.', '')) ?>"
                                readonly
                            >
                            <small class="text-muted">
                                Apertura + ventas en efectivo + neto de ingresos/egresos manuales.
                            </small>
                        </div>
                        <div class="mb-2">
                            <label class="form-label">Efectivo contado</label>
                            <input
                                id="cashRealAmount"
                                type="number"
                                step="0.01"
                                min="0"
                                class="form-control"
                                name="monto_cierre"
                                value="<?= e($closeAmount) ?>"
                                required
                            >
                        </div>
                        <div class="mb-2">
                            <label class="form-label d-block">Diferencia</label>
                            <span id="cashDifferenceBadge" class="badge text-bg-secondary">0.00</span>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Observación</label>
                            <textarea
                                id="cashNotes"
                                class="form-control"
                                name="notas"
                                rows="3"
                                placeholder="Obligatoria si hay sobrante o faltante."
                            ><?= e($closeNotes) ?></textarea>
                            <small id="cashNotesHint" class="text-muted">Sin diferencia, la observación es opcional.</small>
                        </div>
                        <button class="btn btn-outline-primary w-100" type="submit">Cerrar caja</button>
                    </form>
                <?php else: ?>
                    <div class="alert alert-warning mb-0">Debes abrir caja antes de hacer arqueo y cierre.</div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<script>
    (function () {
        const initialModalKey = '<?= e($cashModalOld) ?>';
        const modalMap = {
            movement: 'cashMovementModal',
            transfer: 'cashTransferModal',
            close: 'cashCloseModal',
        };

        const openModal = (modalId) => {
            if (!modalId || typeof bootstrap === 'undefined') {
                return;
            }

            const modalElement = document.getElementById(modalId);
            if (!modalElement) {
                return;
            }

            const instance = new bootstrap.Modal(modalElement);
            instance.show();
        };

        if (Object.prototype.hasOwnProperty.call(modalMap, initialModalKey)) {
            openModal(modalMap[initialModalKey]);
        }

        const form = document.getElementById('closeCashForm');
        if (!form) {
            return;
        }

        const expectedInput = document.getElementById('cashExpectedAmount');
        const realInput = document.getElementById('cashRealAmount');
        const notesInput = document.getElementById('cashNotes');
        const badge = document.getElementById('cashDifferenceBadge');
        const hint = document.getElementById('cashNotesHint');

        const parseNumber = (value) => {
            const parsed = parseFloat(value);
            return Number.isFinite(parsed) ? parsed : 0;
        };

        const updateDifference = () => {
            const expected = parseNumber(expectedInput.value);
            const real = parseNumber(realInput.value);
            const diff = real - expected;
            const rounded = Math.round(diff * 100) / 100;

            badge.textContent = rounded.toFixed(2);
            badge.classList.remove('text-bg-success', 'text-bg-danger', 'text-bg-secondary');

            if (rounded > 0.009) {
                badge.classList.add('text-bg-success');
            } else if (rounded < -0.009) {
                badge.classList.add('text-bg-danger');
            } else {
                badge.classList.add('text-bg-secondary');
            }

            const requiresNotes = Math.abs(rounded) >= 0.01;
            notesInput.required = requiresNotes;
            hint.textContent = requiresNotes
                ? 'Hay diferencia: la observación es obligatoria.'
                : 'Sin diferencia, la observación es opcional.';
        };

        realInput.addEventListener('input', updateDifference);
        expectedInput.addEventListener('input', updateDifference);
        updateDifference();
    })();
</script>
