@extends('layouts.app')

@section('title', 'Caja | Veltrix v2')

@section('topbar_actions')
    @if ($current)
        <button type="button" class="btn btn-outline-primary btn-sm vx-topbar-action d-inline-flex align-items-center gap-1" data-bs-toggle="modal" data-bs-target="#cajaMovimientoModal">
            <i class="bx bx-transfer"></i>
            <span>Ingresos / egresos</span>
        </button>
        <button type="button" class="btn btn-outline-secondary btn-sm vx-topbar-action d-inline-flex align-items-center gap-1" data-bs-toggle="modal" data-bs-target="#cajaTraspasoModal" @disabled($transferTargets->isEmpty())>
            <i class="bx bx-git-compare"></i>
            <span>Traspaso cajas</span>
        </button>
        <button type="button" class="btn btn-danger btn-sm vx-topbar-action d-inline-flex align-items-center gap-1" data-bs-toggle="modal" data-bs-target="#cajaCierreModal">
            <i class="bx bx-lock-alt"></i>
            <span>Arqueo y cierre</span>
        </button>
    @endif
@endsection

@section('content')
    @if (session('status'))
        <div class="alert alert-success">{{ session('status') }}</div>
    @endif

    @if (session('error'))
        <div class="alert alert-danger">{{ session('error') }}</div>
    @endif

    @if ($errors->any())
        <div class="alert alert-danger">
            <div class="fw-semibold mb-1">No se pudo completar la acción en caja:</div>
            <ul class="mb-0 ps-3">
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif

    <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">Caja actual</span>
                    <h2 class="h6 mb-1">{{ $current ? 'Abierta' : 'Sin apertura' }}</h2>
                    <small class="text-muted">
                        @if ($current)
                            Desde {{ optional($current->fecha_apertura)->format('Y-m-d H:i') ?: $current->fecha_apertura }}
                        @else
                            Abre caja para operar
                        @endif
                    </small>
                </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">Efectivo esperado</span>
                    <h2 class="h5 mb-0">{{ number_format((float) $currentExpected, 2) }}</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">Ventas del turno</span>
                        <h2 class="h5 mb-0">{{ number_format((float) ($currentSales['ventas_total'] ?? 0), 2) }}</h2>
                        <small class="text-muted">{{ (int) ($currentSales['ventas_count'] ?? 0) }} ventas</small>
                    </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">Ajustes (sin ventas POS)</span>
                    @php
                        $neto = (float) ($currentAdjustments['neto_ajustes'] ?? 0);
                    @endphp
                    <h2 class="h5 mb-0 {{ $neto < 0 ? 'text-danger' : ($neto > 0 ? 'text-success' : '') }}">
                        {{ number_format($neto, 2) }}
                    </h2>
                    <small class="text-muted">
                        Ing: {{ number_format((float) ($currentAdjustments['total_ingresos'] ?? 0), 2) }}
                        | Egr: {{ number_format((float) ($currentAdjustments['total_egresos'] ?? 0), 2) }}
                    </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 actual</h2>

                    @if ($current)
                        <div class="small mb-3">
                            <div><strong>Caja:</strong> {{ $current->caja?->nombre ?? 'General' }}</div>
                            <div><strong>Sucursal:</strong> {{ $current->caja?->sucursal?->nombre ?? 'Sin sucursal' }}</div>
                            <div><strong>Monto apertura:</strong> {{ number_format((float) $current->monto_apertura, 2) }}</div>
                            <div><strong>Estado:</strong> {{ $current->estado }}</div>
                        </div>

                    @else
                        <div class="alert alert-warning mb-3">No tienes caja abierta en este momento.</div>

                        <form method="POST" action="{{ route('caja.open') }}">
                            @csrf
                            <div class="mb-2">
                                <label class="form-label" for="caja_id">Caja</label>
                                <select class="form-select" id="caja_id" name="caja_id" required>
                                    <option value="">Selecciona una caja...</option>
                                    @foreach ($cashBoxes as $box)
                                        <option value="{{ $box->id }}">{{ $box->nombre }}{{ $box->sucursal ? ' - '.$box->sucursal->nombre : '' }}</option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="mb-2">
                                <label class="form-label" for="monto_apertura">Monto apertura</label>
                                <input class="form-control" id="monto_apertura" name="monto_apertura" type="number" min="0" step="0.01" required>
                            </div>
                            <div class="mb-2">
                                <label class="form-label" for="notas">Notas</label>
                                <textarea class="form-control" id="notas" name="notas" rows="2"></textarea>
                            </div>
                            <button class="btn btn-primary w-100" type="submit" @disabled($cashBoxes->isEmpty())>Abrir caja</button>
                        </form>
                    @endif
                </div>
            </div>

            @if ($current)
                <div class="card border-0 shadow-sm mb-3">
                    <div class="card-body">
                        <h2 class="h6 mb-3">Traspasos pendientes</h2>

                        <div class="small text-muted mb-1">Pendientes entrantes: {{ $pendingIncomingTransfers->count() }}</div>
                        <div class="small text-muted mb-2">Pendientes salientes: {{ $pendingOutgoingTransfers->count() }}</div>

                        @if ($pendingIncomingTransfers->isNotEmpty())
                            <div class="border rounded p-2 mb-2">
                                <div class="fw-semibold small mb-2">Pendientes por aprobar</div>
                                @foreach ($pendingIncomingTransfers as $pending)
                                    <div class="border rounded p-2 mb-2">
                                        <div class="small">
                                            <strong>#{{ $pending->id }}</strong> · {{ number_format((float) $pending->monto, 2) }}<br>
                                            {{ $pending->concepto }}<br>
                                            Origen: {{ $pending->usuarioOrigen?->nombre ?? 'N/A' }}
                                        </div>
                                        <div class="d-flex gap-2 mt-2">
                                            <form method="POST" action="{{ route('caja.transfers.approve', $pending) }}" class="w-100">
                                                @csrf
                                                <button class="btn btn-sm btn-success w-100" type="submit">Aprobar</button>
                                            </form>
                                            <form method="POST" action="{{ route('caja.transfers.reject', $pending) }}" class="w-100">
                                                @csrf
                                                <button class="btn btn-sm btn-outline-danger w-100" type="submit">Rechazar</button>
                                            </form>
                                        </div>
                                    </div>
                                @endforeach
                            </div>
                        @endif

                        @if ($pendingOutgoingTransfers->isNotEmpty())
                            <div class="border rounded p-2">
                                <div class="fw-semibold small mb-2">Pendientes enviados</div>
                                @foreach ($pendingOutgoingTransfers as $pending)
                                    <div class="small border-bottom pb-2 mb-2">
                                        <strong>#{{ $pending->id }}</strong> · {{ number_format((float) $pending->monto, 2) }}<br>
                                        {{ $pending->concepto }}<br>
                                        Destino: {{ $pending->usuarioDestino?->nombre ?? 'N/A' }}
                                    </div>
                                @endforeach
                            </div>
                        @endif
                    </div>
                </div>
            @endif

            <div class="card border-0 shadow-sm">
                <div class="card-body">
                    <h2 class="h6 mb-2">Cajas configuradas</h2>
                    <ul class="list-group list-group-flush">
                        @forelse ($cashBoxes as $box)
                            <li class="list-group-item px-0 d-flex justify-content-between">
                                <span>{{ $box->nombre }}</span>
                                <small class="text-muted">{{ $box->sucursal?->nombre ?? 'General' }}</small>
                            </li>
                        @empty
                            <li class="list-group-item px-0 text-muted">No hay cajas configuradas.</li>
                        @endforelse
                    </ul>
                </div>
            </div>
        </div>

        <div class="col-lg-8">
            <div class="row g-3 mb-3">
                <div class="col-md-4">
                    <div class="card border-0 shadow-sm h-100">
                        <div class="card-body">
                            <span class="metric-label">Cierres</span>
                            <h2 class="h5 mb-0">{{ (int) ($historySummary['total_cierres'] ?? 0) }}</h2>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card border-0 shadow-sm h-100">
                        <div class="card-body">
                            <span class="metric-label">Esperado</span>
                            <h2 class="h6 mb-0">{{ number_format((float) ($historySummary['total_esperado'] ?? 0), 2) }}</h2>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card border-0 shadow-sm h-100">
                        <div class="card-body">
                            <span class="metric-label">Contado</span>
                            <h2 class="h6 mb-0">{{ number_format((float) ($historySummary['total_contado'] ?? 0), 2) }}</h2>
                        </div>
                    </div>
                </div>
            </div>

            <div class="card border-0 shadow-sm mb-3">
                <div class="card-body">
                    <h2 class="h6 mb-3">Movimientos del turno actual</h2>
                    <div class="table-responsive">
                        <table class="table table-sm table-striped align-middle mb-0">
                            <thead>
                                <tr>
                                    <th>Fecha</th>
                                    <th>Tipo</th>
                                    <th>Concepto</th>
                                    <th class="text-end">Monto</th>
                                </tr>
                            </thead>
                            <tbody>
                                @forelse ($currentMovements as $movement)
                                    <tr>
                                        <td>{{ optional($movement->created_at)->format('Y-m-d H:i') ?: $movement->created_at }}</td>
                                        <td class="text-capitalize">{{ $movement->tipo }}</td>
                                        <td>{{ $movement->concepto ?: 'N/A' }}</td>
                                        <td class="text-end">{{ number_format((float) $movement->monto, 2) }}</td>
                                    </tr>
                                @empty
                                    <tr>
                                        <td colspan="4" class="text-center text-muted py-3">Sin movimientos en el turno actual.</td>
                                    </tr>
                                @endforelse
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <div class="card border-0 shadow-sm">
                <div class="card-body">
                    <h2 class="h6 mb-3">Historial de cierres</h2>
                    <div class="table-responsive">
                        <table class="table table-striped table-hover table-sm align-middle mb-0">
                            <thead>
                                <tr>
                                    <th>Fecha cierre</th>
                                    <th>Cajero</th>
                                    <th>Sucursal</th>
                                    <th>Caja</th>
                                    <th>Esperado</th>
                                    <th>Contado</th>
                                    <th>Diferencia</th>
                                </tr>
                            </thead>
                            <tbody>
                                @forelse ($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');
                                    @endphp
                                    <tr>
                                        <td>{{ $item->fecha_cierre }}</td>
                                        <td>{{ $item->cajero ?? 'N/A' }}</td>
                                        <td>{{ $item->sucursal ?? 'Sin sucursal' }}</td>
                                        <td>{{ $item->caja ?? 'General' }}</td>
                                        <td>{{ number_format((float) $item->monto_esperado, 2) }}</td>
                                        <td>{{ number_format((float) $item->monto_real, 2) }}</td>
                                        <td><span class="badge {{ $diffClass }}">{{ number_format($difference, 2) }}</span></td>
                                    </tr>
                                @empty
                                    <tr>
                                        <td colspan="7" class="text-center text-muted py-3">No hay cierres registrados.</td>
                                    </tr>
                                @endforelse
                            </tbody>
                        </table>
                    </div>

                    @if (! $canViewAllClosings)
                        <small class="text-muted d-block mt-2">Viendo solo cierres de tu usuario.</small>
                    @endif
                </div>
            </div>
        </div>
    </div>

    @if ($current)
        <div class="modal fade" id="cajaMovimientoModal" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content">
                    <form method="POST" action="{{ route('caja.movements.store') }}">
                        @csrf
                        <div class="modal-header">
                            <h5 class="modal-title">Ingresos / egresos</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
                        </div>
                        <div class="modal-body">
                            <div class="mb-2">
                                <label class="form-label" for="tipo">Tipo</label>
                                <select class="form-select" id="tipo" name="tipo" required>
                                    <option value="ingreso">Ingreso</option>
                                    <option value="egreso">Egreso</option>
                                </select>
                            </div>
                            <div class="mb-2">
                                <label class="form-label" for="concepto">Concepto</label>
                                <input class="form-control" id="concepto" name="concepto" maxlength="160" required>
                            </div>
                            <div class="mb-2">
                                <label class="form-label" for="monto">Monto</label>
                                <input class="form-control" id="monto" name="monto" type="number" min="0.01" step="0.01" required>
                            </div>
                            <div class="mb-2">
                                <label class="form-label" for="observacion">Observación</label>
                                <textarea class="form-control" id="observacion" name="observacion" rows="2"></textarea>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancelar</button>
                            <button class="btn btn-primary" type="submit">Registrar movimiento</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <div class="modal fade" id="cajaTraspasoModal" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content">
                    <form method="POST" action="{{ route('caja.transfers.store') }}">
                        @csrf
                        <div class="modal-header">
                            <h5 class="modal-title">Traspaso entre cajas</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
                        </div>
                        <div class="modal-body">
                            <div class="mb-2">
                                <label class="form-label" for="apertura_destino_id">Caja destino</label>
                                <select class="form-select" id="apertura_destino_id" name="apertura_destino_id" required>
                                    <option value="">Selecciona destino...</option>
                                    @foreach ($transferTargets as $target)
                                        <option value="{{ $target->id }}">
                                            Apertura #{{ $target->id }} · {{ $target->usuario?->nombre ?? 'N/A' }} · {{ $target->caja?->nombre ?? 'Caja' }}
                                        </option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="mb-2">
                                <label class="form-label" for="monto_traspaso">Monto</label>
                                <input class="form-control" id="monto_traspaso" name="monto" type="number" min="0.01" step="0.01" required>
                            </div>
                            <div class="mb-2">
                                <label class="form-label" for="concepto_traspaso">Concepto</label>
                                <input class="form-control" id="concepto_traspaso" name="concepto" maxlength="160" required>
                            </div>
                            <div class="mb-2">
                                <label class="form-label" for="observacion_traspaso">Observación</label>
                                <textarea class="form-control" id="observacion_traspaso" name="observacion" rows="2"></textarea>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancelar</button>
                            <button class="btn btn-secondary" type="submit" @disabled($transferTargets->isEmpty())>Enviar traspaso</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <div class="modal fade" id="cajaCierreModal" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content">
                    <form method="POST" action="{{ route('caja.close') }}">
                        @csrf
                        <div class="modal-header">
                            <h5 class="modal-title">Arqueo y cierre</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
                        </div>
                        <div class="modal-body">
                            <div class="mb-2">
                                <label class="form-label" for="monto_real">Monto real contado</label>
                                <input class="form-control" id="monto_real" name="monto_real" type="number" min="0" step="0.01" required>
                            </div>
                            <div class="mb-2">
                                <label class="form-label" for="observacion_cierre">Observación cierre</label>
                                <textarea class="form-control" id="observacion_cierre" name="observacion_cierre" rows="2"></textarea>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancelar</button>
                            <button class="btn btn-danger" type="submit">Cerrar caja</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    @endif
@endsection
