<x-app-layout>
    <x-slot name="title">
        Caja Chica
    </x-slot>

    @if(!$sesion)
        <!-- Estado: Sin Sesión Abierta -->
        <div class="row justify-content-center mb-5">
            <div class="col-md-6 col-lg-5 mt-4">
                <div class="card border-0 shadow-sm rounded-4 text-center p-4">
                    <div class="card-body">
                        <div class="rounded-circle bg-primary bg-opacity-10 d-inline-flex align-items-center justify-content-center mb-4" style="width: 80px; height: 80px;">
                            <i class="bi bi-cash-stack text-primary fs-1"></i>
                        </div>
                        <h4 class="fw-bold mb-2">Caja Cerrada</h4>
                        <p class="text-muted mb-4">Abre una nueva sesión de caja para empezar a registrar movimientos en esta sucursal.</p>
                        
                        <form method="POST" action="{{ route('caja.abrir') }}">
                            @csrf
                            <div class="input-group mb-4">
                                <span class="input-group-text bg-light border-end-0">{{ $moneda }} </span>
                                <input type="number" name="monto_apertura" class="form-control border-start-0" placeholder="Monto base de apertura" step="0.01" min="0" required>
                            </div>
                            <button type="submit" class="btn btn-primary rounded-pill fw-bold w-100 py-2 shadow-sm">
                                <i class="bi bi-door-open-fill me-2"></i> Abrir Turno de Caja
                            </button>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        @if($ultimosCierres->count() > 0)
            <div class="card border-0 shadow-sm rounded-4 mt-4">
                <div class="card-header bg-white border-0 pt-4 pb-0 px-4">
                    <h6 class="fw-bold text-muted text-uppercase mb-0">Últimos Cierres</h6>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-hover align-middle mb-0">
                            <thead class="bg-light">
                                <tr>
                                    <th class="ps-4 py-3 text-secondary" style="font-size: 0.75rem;">Apertura</th>
                                    <th class="py-3 text-secondary" style="font-size: 0.75rem;">Cierre</th>
                                    <th class="py-3 text-center text-secondary" style="font-size: 0.75rem;">Diferencia</th>
                                    <th class="pe-4 py-3 text-end text-secondary" style="font-size: 0.75rem;">Acciones</th>
                                </tr>
                            </thead>
                            <tbody class="border-top-0">
                                @foreach($ultimosCierres as $cierre)
                                    <tr>
                                        <td class="ps-4 py-3">
                                            <div class="fw-bold">{{ $cierre->abierta_at->format('d/m/Y') }}</div>
                                            <div class="text-muted small">{{ $cierre->abierta_at->format('H:i') }} - Por {{ $cierre->usuario->name ?? 'N/A' }}</div>
                                        </td>
                                        <td class="py-3">
                                            <div class="fw-bold">{{ $cierre->cerrada_at->format('d/m/Y') }}</div>
                                            <div class="text-muted small">{{ $cierre->cerrada_at->format('H:i') }} - Por {{ $cierre->cerradaPor->name ?? 'N/A' }}</div>
                                        </td>
                                        <td class="py-3 text-center">
                                            @if($cierre->diferencia == 0)
                                                <span class="badge bg-success bg-opacity-10 text-success rounded-pill px-3">Cuadre exacto</span>
                                            @elseif($cierre->diferencia > 0)
                                                <span class="badge bg-info bg-opacity-10 text-info rounded-pill px-3">+S/. {{ number_format($cierre->diferencia, 2) }}</span>
                                            @else
                                                <span class="badge bg-danger bg-opacity-10 text-danger rounded-pill px-3">-S/. {{ number_format(abs($cierre->diferencia), 2) }}</span>
                                            @endif
                                        </td>
                                        <td class="pe-4 py-3 text-end">
                                            <a href="{{ route('caja.sesion', $cierre) }}" class="btn btn-sm btn-light border rounded-circle" title="Ver detalle">
                                                <i class="bi bi-eye text-primary"></i>
                                            </a>
                                        </td>
                                    </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        @endif

    @else
        <!-- Estado: Sesión Abierta -->
        <div class="d-flex justify-content-end gap-2 mb-4">
            <a href="{{ route('caja.historial') }}" class="btn btn-outline-secondary rounded-pill fw-bold bg-white">
                <i class="bi bi-clock-history me-1"></i> Ver Historial
            </a>
            <button type="button" class="btn btn-danger rounded-pill fw-bold shadow-sm" data-bs-toggle="modal" data-bs-target="#cerrarCajaModal">
                <i class="bi bi-door-closed-fill me-1"></i> Cerrar Caja
            </button>
        </div>

        <div class="row g-3 mb-4">
            <!-- Widget Ingresos -->
            <div class="col-md-4">
                <div class="card card-solid bg-gradient-green h-100 border-0 shadow-sm rounded-4">
                    <div class="card-body p-4 position-relative">
                        <i class="bi bi-arrow-down-circle-fill icon-bg"></i>
                        <h6 class="text-uppercase fw-bold text-white-50 mb-1">Total Ingresos (+ Apertura)</h6>
                        <h2>{{ $moneda }} {{ number_format($sesion->monto_apertura + $sesion->total_ingresos, 2) }}</h2>
                        <div class="small text-white-50 mt-2">
                            Apertura: {{ $moneda }} {{ number_format($sesion->monto_apertura, 2) }}
                        </div>
                    </div>
                </div>
            </div>

            <!-- Widget Egresos -->
            <div class="col-md-4">
                <div class="card card-solid bg-gradient-red h-100 border-0 shadow-sm rounded-4">
                    <div class="card-body p-4 position-relative">
                        <i class="bi bi-arrow-up-circle-fill icon-bg"></i>
                        <h6 class="text-uppercase fw-bold text-white-50 mb-1">Total Egresos</h6>
                        <h2>{{ $moneda }} {{ number_format($sesion->total_egresos, 2) }}</h2>
                    </div>
                </div>
            </div>

            <!-- Widget Saldo -->
            <div class="col-md-4">
                <div class="card card-solid bg-gradient-blue h-100 border-0 shadow-sm rounded-4">
                    <div class="card-body p-4 position-relative">
                        <i class="bi bi-wallet2 icon-bg"></i>
                        <h6 class="text-uppercase fw-bold text-white-50 mb-1">Saldo Esperado</h6>
                        @php
                            $saldoEsperado = $sesion->monto_apertura + $sesion->total_ingresos - $sesion->total_egresos;
                        @endphp
                        <h2>{{ $moneda }} {{ number_format($saldoEsperado, 2) }}</h2>
                        <div class="small text-white-50 mt-2">
                            Debe coincidir con la cuenta física
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="card border-0 shadow-sm rounded-4 mb-4">
            <div class="card-header bg-white border-bottom pt-4 px-4 d-flex justify-content-between align-items-center">
                <div>
                    <h5 class="fw-bold mb-0">Movimientos del Turno</h5>
                    <div class="text-muted small mt-1">
                        Turno abierto el {{ $sesion->abierta_at->format('d/m/Y') }} a las {{ $sesion->abierta_at->format('H:i') }}
                    </div>
                </div>
                <button type="button" class="btn btn-primary rounded-pill fw-bold shadow-sm px-4" data-bs-toggle="modal" data-bs-target="#nuevoMovimientoModal">
                    <i class="bi bi-plus-lg me-1"></i> Nuevo Movimiento
                </button>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover align-middle mb-0">
                        <thead class="bg-light">
                            <tr>
                                <th class="ps-4 py-3 text-secondary text-uppercase" style="font-size: 0.75rem; font-weight: 700;">Hora</th>
                                <th class="py-3 text-secondary text-uppercase" style="font-size: 0.75rem; font-weight: 700;">Tipo</th>
                                <th class="py-3 text-secondary text-uppercase" style="font-size: 0.75rem; font-weight: 700;">Concepto / Categoría</th>
                                <th class="py-3 text-secondary text-uppercase" style="font-size: 0.75rem; font-weight: 700;">Comprobante</th>
                                <th class="py-3 text-end text-secondary text-uppercase" style="font-size: 0.75rem; font-weight: 700;">Monto</th>
                                <th class="pe-4 py-3 text-end text-secondary text-uppercase" style="font-size: 0.75rem; font-weight: 700;">Acciones</th>
                            </tr>
                        </thead>
                        <tbody class="border-top-0">
                            @forelse($sesion->movimientosActivos as $movimiento)
                                <tr>
                                    <td class="ps-4 py-3 text-muted small">
                                        {{ $movimiento->created_at->format('H:i') }}
                                    </td>
                                    <td class="py-3">
                                        @if($movimiento->tipo === 'ingreso')
                                            <span class="badge bg-success bg-opacity-10 text-success border border-success border-opacity-25 rounded-pill px-2">Ingreso</span>
                                        @else
                                            <span class="badge bg-danger bg-opacity-10 text-danger border border-danger border-opacity-25 rounded-pill px-2">Egreso</span>
                                        @endif
                                    </td>
                                    <td class="py-3">
                                        <div class="fw-bold text-dark">{{ $movimiento->concepto }}</div>
                                        <div class="text-muted small text-capitalize">{{ str_replace('_', ' ', $movimiento->categoria) }}</div>
                                    </td>
                                    <td class="py-3">
                                        @if($movimiento->comprobante_tipo !== 'ninguno')
                                            <div class="text-dark small"><span class="text-capitalize">{{ $movimiento->comprobante_tipo }}</span> {{ $movimiento->comprobante_numero }}</div>
                                        @else
                                            <span class="text-muted small">—</span>
                                        @endif
                                    </td>
                                    <td class="py-3 text-end">
                                        <div class="fw-bold {{ $movimiento->tipo === 'ingreso' ? 'text-success' : 'text-danger' }}">
                                            {{ $movimiento->tipo === 'ingreso' ? '+' : '-' }} {{ $moneda }} {{ number_format($movimiento->monto, 2) }}
                                        </div>
                                    </td>
                                    <td class="pe-4 py-3 text-end">
                                        <button type="button" class="btn btn-sm btn-light border rounded-circle text-danger" title="Anular movimiento" data-bs-toggle="modal" data-bs-target="#anularModal{{ $movimiento->id }}">
                                            <i class="bi bi-x-lg"></i>
                                        </button>
                                        
                                        <!-- Modal Anular Movimiento -->
                                        <div class="modal fade text-start" id="anularModal{{ $movimiento->id }}" tabindex="-1" aria-hidden="true">
                                            <div class="modal-dialog modal-sm modal-dialog-centered">
                                                <div class="modal-content border-0 shadow-lg rounded-4">
                                                    <div class="modal-body p-4 text-center">
                                                        <div class="text-danger mb-3">
                                                            <i class="bi bi-exclamation-triangle-fill fs-1"></i>
                                                        </div>
                                                        <h5 class="fw-bold mb-3">¿Anular Movimiento?</h5>
                                                        <p class="text-muted small mb-4">Esta acción revertirá el {{ $movimiento->tipo }} por {{ $moneda }} {{ number_format($movimiento->monto, 2) }}.</p>
                                                        
                                                        <form method="POST" action="{{ route('caja.anular', $movimiento) }}">
                                                            @csrf
                                                            @method('PATCH')
                                                            <div class="mb-3 text-start">
                                                                <label class="form-label small fw-bold text-muted">Motivo de anulación <span class="text-danger">*</span></label>
                                                                <input type="text" name="motivo_anulacion" class="form-control form-control-sm" required minlength="5">
                                                            </div>
                                                            <div class="d-flex gap-2 w-100">
                                                                <button type="button" class="btn btn-light rounded-pill fw-bold flex-grow-1" data-bs-dismiss="modal">Cancelar</button>
                                                                <button type="submit" class="btn btn-danger rounded-pill fw-bold flex-grow-1 shadow-sm">Sí, anular</button>
                                                            </div>
                                                        </form>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                            @empty
                                <tr>
                                    <td colspan="6" class="text-center py-5 text-muted">
                                        <i class="bi bi-inbox fs-1 d-block mb-3 text-light"></i>
                                        No hay movimientos registrados en este turno.
                                    </td>
                                </tr>
                            @endforelse
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Modal Cerrar Caja -->
        <div class="modal fade" id="cerrarCajaModal" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content border-0 shadow-lg rounded-4">
                    <div class="modal-header bg-danger text-white border-bottom-0 rounded-top-4 p-4">
                        <h5 class="modal-title fw-bold"><i class="bi bi-door-closed-fill me-2"></i> Cerrar Caja</h5>
                        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body p-4">
                        <form method="POST" action="{{ route('caja.cerrar') }}">
                            @csrf
                            <div class="mb-4 bg-light p-3 rounded-3 text-center">
                                <span class="text-muted small d-block mb-1">Saldo Esperado en Sistema</span>
                                <h3 class="fw-bold mb-0 text-dark">{{ $moneda }} {{ number_format($saldoEsperado, 2) }}</h3>
                            </div>

                            <div class="mb-3">
                                <label class="form-label fw-bold small text-muted">Monto Real Físico (Efectivo/Bancos) <span class="text-danger">*</span></label>
                                <div class="input-group">
                                    <span class="input-group-text bg-white">{{ $moneda }} </span>
                                    <input type="number" name="monto_cierre" class="form-control" step="0.01" min="0" placeholder="0.00" required>
                                </div>
                                <div class="form-text">Si hay diferencia con el saldo esperado, se registrará como sobrante o faltante.</div>
                            </div>

                            <div class="mb-4">
                                <label class="form-label fw-bold small text-muted">Notas de Cierre (Opcional)</label>
                                <textarea name="notas_cierre" class="form-control" rows="2" placeholder="Observaciones sobre diferencias, billetes falsos, etc."></textarea>
                            </div>

                            <div class="d-flex justify-content-end gap-2 mt-4 pt-3 border-top">
                                <button type="button" class="btn btn-light rounded-pill border fw-bold px-4" data-bs-dismiss="modal">Cancelar</button>
                                <button type="submit" class="btn btn-danger rounded-pill fw-bold shadow-sm px-4">
                                    <i class="bi bi-check-lg me-1"></i> Confirmar Cierre
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <!-- Modal Nuevo Movimiento -->
        <div class="modal fade" id="nuevoMovimientoModal" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered modal-lg">
                <div class="modal-content border-0 shadow-lg rounded-4">
                    <div class="modal-header bg-light border-bottom-0 pb-0 rounded-top-4 pt-4 px-4">
                        <h5 class="modal-title fw-bold"><i class="bi bi-cash-coin text-primary me-2"></i> Registrar Movimiento</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body p-4">
                        <form method="POST" action="{{ route('caja.movimiento') }}">
                            @csrf
                            <div class="row g-3">
                                <div class="col-md-6">
                                    <label class="form-label fw-bold small text-muted">Tipo <span class="text-danger">*</span></label>
                                    <div class="d-flex gap-3 mt-1">
                                        <div class="form-check form-check-inline">
                                            <input class="form-check-input mt-2" type="radio" name="tipo" id="tipoIngreso" value="ingreso" checked>
                                            <label class="form-check-label badge bg-success bg-opacity-10 text-success rounded-pill px-3 py-2 border border-success border-opacity-25" for="tipoIngreso">Ingreso (+)</label>
                                        </div>
                                        <div class="form-check form-check-inline">
                                            <input class="form-check-input mt-2" type="radio" name="tipo" id="tipoEgreso" value="egreso">
                                            <label class="form-check-label badge bg-danger bg-opacity-10 text-danger rounded-pill px-3 py-2 border border-danger border-opacity-25" for="tipoEgreso">Egreso (-)</label>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label fw-bold small text-muted">Monto ({{ $moneda }} ) <span class="text-danger">*</span></label>
                                    <input type="number" name="monto" class="form-control" step="0.01" min="0.01" required>
                                </div>
                                
                                <div class="col-12 mt-4 pt-4 border-top">
                                    <div class="row g-3">
                                        <div class="col-md-6">
                                            <label class="form-label fw-bold small text-muted">Categoría <span class="text-danger">*</span></label>
                                            <select name="categoria" class="form-select tom-select" required>
                                                <optgroup label="Ingresos">
                                                    <option value="venta_efectivo">Venta (Efectivo)</option>
                                                    <option value="venta_tarjeta">Venta (Tarjeta/POS)</option>
                                                    <option value="venta_transferencia">Venta (Transferencia/Yape/Plin)</option>
                                                    <option value="adelanto_cliente">Adelanto Cliente</option>
                                                </optgroup>
                                                <optgroup label="Egresos">
                                                    <option value="pago_proveedor">Pago a Proveedor</option>
                                                    <option value="gasto_operativo">Gasto Operativo / Movilidad</option>
                                                    <option value="pago_servicio">Pago de Servicio (Luz, Agua, etc.)</option>
                                                    <option value="devolucion_cliente">Devolución a Cliente</option>
                                                    <option value="retiro_caja">Retiro (Depósito Bco / Dueño)</option>
                                                </optgroup>
                                                <option value="otro">Otro</option>
                                            </select>
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label fw-bold small text-muted">Concepto <span class="text-danger">*</span></label>
                                            <input type="text" name="concepto" class="form-control" placeholder="Ej. Pago taxis mercadería, Venta de mostrador, etc." required maxlength="200">
                                        </div>
                                    </div>
                                </div>

                                <div class="col-12 mt-4 pt-4 border-top">
                                    <h6 class="fw-bold mb-3 small text-muted">Comprobante (Opcional)</h6>
                                    <div class="row g-3">
                                        <div class="col-md-4">
                                            <label class="form-label small">Documento</label>
                                            <select name="comprobante_tipo" class="form-select tom-select" id="comprobante_tipo">
                                                <option value="ninguno">Ninguno/Recibo interno</option>
                                                <option value="boleta">Boleta de Venta</option>
                                                <option value="factura">Factura</option>
                                                <option value="ticket">Ticket POS</option>
                                            </select>
                                        </div>
                                        <div class="col-md-8" id="divSerie">
                                            <label class="form-label small">N° Comprobante</label>
                                            <input type="text" name="comprobante_numero" class="form-control" placeholder="Ej. B001-000451">
                                        </div>
                                    </div>
                                    <div class="row g-3 mt-1 d-none" id="divFactura">
                                        <div class="col-md-4">
                                            <label class="form-label small">RUC Cliente/Prov.</label>
                                            <input type="text" name="ruc_cliente" class="form-control" maxlength="11">
                                        </div>
                                        <div class="col-md-8">
                                            <label class="form-label small">Razón Social</label>
                                            <input type="text" name="razon_social_cliente" class="form-control">
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="mt-4 pt-3 border-top text-end">
                                <button type="button" class="btn btn-light rounded-pill border fw-bold px-4 me-2 shadow-sm" data-bs-dismiss="modal">Cancelar</button>
                                <button type="submit" class="btn btn-primary rounded-pill fw-bold shadow-sm px-4">
                                    <i class="bi bi-save me-1"></i> Guardar Movimiento
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        @push('scripts')
        <script>
            document.addEventListener('DOMContentLoaded', function() {
                const compTipo = document.getElementById('comprobante_tipo');
                const divFactura = document.getElementById('divFactura');
                const inputRuc = document.querySelector('input[name="ruc_cliente"]');
                const inputRazon = document.querySelector('input[name="razon_social_cliente"]');

                compTipo.addEventListener('change', function() {
                    if (this.value === 'factura') {
                        divFactura.classList.remove('d-none');
                        inputRuc.setAttribute('required', 'required');
                        inputRazon.setAttribute('required', 'required');
                    } else {
                        divFactura.classList.add('d-none');
                        inputRuc.removeAttribute('required');
                        inputRazon.removeAttribute('required');
                    }
                });
            });
        </script>
        @endpush

    @endif
</x-app-layout>
