@extends('layouts.master')
@section('title') Inicio @endsection
@section('content')
<!-- this is breadcrumbs -->
@component('components.breadcrumb')
@slot('li_1') Inicio @endslot
@slot('li_2') Panel Catastro @endslot
@slot('title') Registro de Pagos @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-primary btn-sm px-4 mt-0 mb-3" 
                    data-bs-toggle="modal" 
                    data-bs-target="#modalAbrirCaja">
                    <i class="fas fa-plus"></i>  Abrir Caja
                </button>

            


                <div class="table-responsive">
                    <table id="tablaRecibos" class="table table-striped mb-0 table-hover">
                        <thead class="table-light">
                            <tr>
                                <th>ID</th>
                                <th>Nombre</th>
                                <th>Saldo Inicial</th>
                                <th>Saldo Actual</th>
                                <th>Estado</th>
                                <th>Acciones</th>
                            </tr>
                        </thead>
                        <tbody>
                            @forelse($cajas as $caja)
                                <tr>
                                    <td>{{ $caja->id_caja }}</td>
                                    <td>{{ $caja->nombre }}</td>
                                    <td>S/ {{ number_format($caja->saldo_inicial, 2) }}</td>
                                    <td>S/ {{ number_format($caja->saldo_actual, 2) }}</td>
                                    <td>
                                        @if($caja->estado === 'abierta')
                                            <span class="badge bg-success">Abierta</span>
                                        @else
                                            <span class="badge bg-secondary">Cerrada</span>
                                        @endif
                                    </td>
                                    <td>
                                        <a href="route('caja.historial', $caja->id_caja)" class="btn btn-info btn-sm">
                                            <i class="fas fa-history"></i> Historial
                                        </a>
                                        @if($caja->estado === 'abierta')
                                            <button type="button" 
                                                    class="btn btn-danger btn-sm btn-cerrar-caja" 
                                                    data-id="{{ $caja->id_caja }}">
                                                <i class="fas fa-lock"></i> Cerrar
                                            </button>
                                        @else
                                            <button class="btn btn-secondary btn-sm" disabled>
                                                <i class="fas fa-lock"></i> Cerrada
                                            </button>
                                        @endif

                                    </td>
                                </tr>
                            @empty
                                
                            @endforelse
                        </tbody>
                    </table>






                </div>
            </div>
            <!--end card-body-->
        </div>
        <!--end card-->
    </div>
    <!--end col-->
</div>



<!-- Modal -->

<!-- Modal Abrir Caja -->
<div class="modal fade" id="modalAbrirCaja" tabindex="-1" aria-labelledby="modalAbrirCajaLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header bg-primary text-white">
        <h5 class="modal-title" id="modalAbrirCajaLabel">
          <i class="fas fa-cash-register"></i> Abrir Caja
        </h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
      </div>
      <div class="modal-body">
        <form id="formAbrirCaja">
          @csrf
          <div class="row">
            <div class="col-md-6 mb-3">
              <label for="nombre" class="form-label">Nombre de Caja</label>
              <input type="text" name="nombre" id="nombre" class="form-control" required>
            </div>
            <div class="col-md-6 mb-3">
              <label for="saldo_inicial" class="form-label">Saldo Inicial</label>
              <input type="number" step="0.01" name="saldo_inicial" id="saldo_inicial" class="form-control" required>
            </div>
            <div class="col-12 mb-3">
              <label for="descripcion" class="form-label">Descripción</label>
              <input type="text" name="descripcion" id="descripcion" class="form-control">
            </div>
          </div>
          <button type="submit" class="btn btn-primary w-100">
            <i class="fas fa-check"></i> Guardar
          </button>
        </form>
      </div>
    </div>
  </div>
</div>










<!--end row-->


@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>
<!-- tablas -->
<script>
    $(document).ready(function () {
        $("#tablaRecibos").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('#tablaRecibos_wrapper .col-md-6:eq(0)');
    });
</script>

<script>
$(document).ready(function () {
    $('#formAbrirCaja').submit(function(e){
        e.preventDefault();

        $.ajax({
            url: "{{ route('caja.abrir') }}",
            method: "POST",
            data: $(this).serialize(),
            success: function(response){
                $('#modalAbrirCaja').modal('hide');
                Swal.fire({
                    icon: 'success',
                    title: 'Caja abierta',
                    text: response.message ?? 'Caja abierta correctamente',
                    timer: 2000,
                    showConfirmButton: false
                });
                setTimeout(() => location.reload(), 2000);
            },
            error: function(xhr){
                let errors = xhr.responseJSON?.errors;
                let mensaje = 'Ocurrió un error al abrir la caja';
                if(errors){
                    mensaje = Object.values(errors).join('<br>');
                }
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    html: mensaje
                });
            }
        });
    });
});
</script>
<script>
$(document).on('click', '.btn-cerrar-caja', function() {
    let id = $(this).data('id');

    Swal.fire({
        title: '¿Cerrar caja?',
        text: "Esta acción no se puede deshacer.",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Sí, cerrar',
        cancelButtonText: 'Cancelar'
    }).then((result) => {
        if (result.isConfirmed) {
            $.ajax({
                url: "{{ url('caja/cerrar') }}/" + id,
                type: "POST",
                data: {
                    _token: "{{ csrf_token() }}"
                },
                success: function(response) {
                    Swal.fire({
                        title: '¡Caja cerrada!',
                        text: response.message,
                        icon: 'success',
                        timer: 1500,
                        showConfirmButton: false
                    }).then(() => {
                        location.reload();
                    });
                },
                error: function(xhr) {
                    Swal.fire({
                        title: 'Error',
                        text: 'No se pudo cerrar la caja.',
                        icon: 'error'
                    });
                }
            });
        }
    });
});
</script>
@endsection
