@extends('layouts.master')
@section('title') Inicio @endsection
@section('content')
<!-- this is breadcrumbs -->
@component('components.breadcrumb')
@slot('li_1') Inicio @endslot
@slot('li_2') Panel Caja @endslot
@slot('title') Caja @endslot
@endcomponent

<!-- start page content -->
<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-body mb-n3">
                <button type="button" class="btn btn-de-primary btn-sm px-4 mt-0 mb-3" 
                    data-bs-toggle="modal" 
                    data-bs-target="#modalAperturaCaja">
                    <i class="fas fa-plus"></i> Abrir Nueva Caja
                </button>

                
                <div class="table-responsive">
                    
                    <table id="tablaSemestres" class="table table-striped mb-0 table-hover">
                        <thead class="table-light">
                            <tr>
                                <th>#</th>
                                <th>Nombre</th>
                                <th>Fecha Apertura</th>
                                <th>Saldo Inicial</th>
                                <th>Saldo Actual</th>
                                <th>Estado</th>
                                <th class="text-end">Acciones</th>
                            </tr>
                        </thead>
                        <tbody>
                            @forelse ($cajas as $caja)
                                <tr>
                                    <td>{{ $loop->iteration }}</td>
                                    <td>{{ $caja->nombre }}</td>
                                    <td>{{ \Carbon\Carbon::parse($caja->fecha_apertura)->format('d/m/Y H:i') }}</td>
                                    <td>S/ {{ number_format($caja->apertura, 2) }}</td>
                                    <td>
                                        @if ($caja->fecha_cierre)
                                            S/ {{ number_format($caja->saldo_final, 2) }}
                                        @else
                                            S/ {{ number_format($caja->saldo, 2) }}
                                        @endif
                                    </td>
                                    <td>
                                        @if ($caja->fecha_cierre)
                                            <span class="badge bg-danger">Cerrada</span>
                                        @else
                                            <span class="badge bg-success">Abierta</span>
                                        @endif
                                    </td>
                                    <td class="text-end">
                                        <a href="javascript:void(0)" 
                                            class="btn btn-sm btn-outline-primary" 
                                            onclick="verDetalleCaja({{ $caja->id_caja }})">
                                            <i class="bi bi-eye-fill"></i>
                                        </a>

                                        @if (!$caja->fecha_cierre)
                                            <button class="btn btn-sm btn-outline-danger" onclick="cerrarCaja({{ $caja->id_caja }})">
                                                <i class="bi bi-lock-fill"></i>
                                            </button>
                                        @endif
                                    </td>
                                </tr>
                            @empty
                                <tr>
                                    <td colspan="7" class="text-center text-muted">No hay cajas registradas.</td>
                                </tr>
                            @endforelse
                        </tbody>
                    </table>
                </div>
            </div>
            <!--end card-body-->
        </div>
        <!--end card-->
    </div>
    <!--end col-->
</div>

<!-- Modal: Apertura de Caja -->
<div class="modal fade" id="modalAperturaCaja" tabindex="-1" aria-labelledby="modalAperturaCajaLabel" aria-hidden="true">
    <div class="modal-dialog">
        <form id="formAperturaCaja">
            @csrf
            <div class="modal-content">
                <div class="modal-header bg-success text-white">
                    <h5 class="modal-title" id="modalAperturaCajaLabel"><i class="bi bi-box-arrow-in-down me-1"></i> Abrir Nueva Caja</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Cerrar"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="nombre" class="form-label">Nombre de la Caja</label>
                        <input type="text" class="form-control" name="nombre" required>
                    </div>
                    <div class="mb-3">
                        <label for="apertura" class="form-label">Monto de Apertura (S/)</label>
                        <input type="number" class="form-control" name="apertura" step="0.01" min="0" required>
                    </div>
                    <div class="mb-3">
                        <label for="observacion" class="form-label">Observación</label>
                        <textarea class="form-control" 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 type="submit" class="btn btn-success"><i class="bi bi-check-circle me-1"></i> Abrir Caja</button>
                </div>
            </div>
        </form>
    </div>
</div>

<div class="modal fade" id="modalDetalleCaja" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-scrollable"> {{-- Scroll largo --}}
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Detalle de Caja</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
            </div>
            <div class="modal-body" id="contenidoDetalleCaja">
                <div class="text-center">
                    <div class="spinner-border text-primary" role="status"></div>
                    <p class="mt-2">Cargando detalles...</p>
                </div>
            </div>
        </div>
    </div>
</div>



@endsection
@section('script')
<!-- jQuery y DataTables -->

<!-- jQuery y DataTables -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>

<!-- DataTables Buttons -->
<script src="https://cdn.datatables.net/buttons/2.3.6/js/dataTables.buttons.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/vfs_fonts.js"></script>
<script src="https://cdn.datatables.net/buttons/2.3.6/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.3.6/js/buttons.print.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.3.6/js/buttons.colVis.min.js"></script>

<!-- DataTables CSS -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/jquery.dataTables.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.3.6/css/buttons.dataTables.min.css">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
    $(document).ready(function () {
        $("#tablaSemestres").DataTable({
            "responsive": true,
            "lengthChange": true,
            "autoWidth": false,
            "buttons": [
                {
                    extend: 'collection',
                    text: 'Opciones',
                    buttons: [
                        { extend: 'copy', text: 'Copiar' },
                        { extend: 'csv', text: 'CSV' },
                        { extend: 'excel', text: 'Excel', title: 'Periodos Académicos' },
                        { extend: 'pdf', text: 'PDF' },
                        { extend: 'print', text: 'Imprimir' }
                    ]
                },
                { extend: 'colvis', text: 'Visibilidad de Columna' }
            ],
            "paging": true,
            "searching": true,
            "info": true,
            "language": {
                "search": "Buscar:",
                "lengthMenu": "Mostrar _MENU_ registros por página",
                "info": "Mostrando _START_ a _END_ de _TOTAL_ entradas",
                "paginate": {
                    "first": "Primero",
                    "previous": "Anterior",
                    "next": "Siguiente",
                    "last": "Último"
                }
            }
        }).buttons().container().appendTo('#tablaSemestres_wrapper .col-md-6:eq(0)');
    });
</script>
<!-- abrir caja -->
<script>
    document.getElementById('formAperturaCaja').addEventListener('submit', function(e) {
        e.preventDefault();

        const form = this;
        const formData = new FormData(form);

        fetch("{{ route('caja.abrir') }}", {
            method: "POST",
            headers: {
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            },
            body: formData
        })
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                Swal.fire({
                    icon: 'success',
                    title: 'Caja abierta correctamente',
                    timer: 1500,
                    showConfirmButton: false
                }).then(() => {
                    location.reload();
                });
            } else {
                Swal.fire('Error', data.message || 'No se pudo abrir la caja.', 'error');
            }
        })
        .catch(() => {
            Swal.fire('Error', 'Ocurrió un error en el servidor.', 'error');
        });
    });
</script>


<!-- cerrar caja -->
<script>
    function cerrarCaja(id) {
        Swal.fire({
            title: '¿Cerrar esta caja?',
            text: 'No podrás registrar más movimientos en esta caja una vez cerrada.',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Sí, cerrar',
            cancelButtonText: 'Cancelar'
        }).then((result) => {
            if (result.isConfirmed) {
                fetch(`/caja/cerrar/${id}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                    }
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Error al cerrar la caja');
                    }
                    return response.json();
                })
                .then(data => {
                    Swal.fire('Caja cerrada', data.message, 'success')
                        .then(() => location.reload());
                })
                .catch(() => {
                    Swal.fire('Error', 'No se pudo cerrar la caja.', 'error');
                });
            }
        });
    }
</script>

<script>
    function verDetalleCaja(id) {
    const modal = new bootstrap.Modal(document.getElementById('modalDetalleCaja'));
    document.getElementById('contenidoDetalleCaja').innerHTML = `
        <div class="text-center">
            <div class="spinner-border text-primary" role="status"></div>
            <p class="mt-2">Cargando detalles...</p>
        </div>
    `;
    modal.show();

    fetch(`/caja/detalle/${id}`)
        .then(res => res.text())
        .then(html => {
            document.getElementById('contenidoDetalleCaja').innerHTML = html;
        })
        .catch(() => {
            document.getElementById('contenidoDetalleCaja').innerHTML = `
                <div class="alert alert-danger">No se pudo cargar el detalle.</div>
            `;
        });
}

</script>
@endsection
