@extends('layouts.master')
@section('title') Inicio @endsection
@section('content')
<!-- this is breadcrumbs -->
@component('components.breadcrumb')
@slot('li_1') Inicio @endslot
@slot('li_2') Panel Facturación @endslot
@slot('title') Categoria Tarifa @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="#modalCrearCategoria">
                    <i class="fas fa-plus"></i>  Nueva Categoria Tarifa
                </button>
                <div class="table-responsive">
                    <table id="tablaSectores" class="table table-striped mb-0 table-hover">
                        <thead class="table-light">
                            <tr>
                                <th>#</th>
                                <th>Clase</th>
                                <th>Nombre</th>
                                <th>Rango (m³)</th>
                                <th>Descripción</th>
                                <th>Acciones</th>
                            </tr>
                        </thead>
                        <tbody>
                        @foreach ($categorias as $i => $cat)
                            <tr>
                            <td>{{ $i + 1 }}</td>
                            <td>{{ $cat->claseTarifa->nombre_clase ?? '-' }}</td>
                            <td>{{ $cat->nombre_categoria }}</td>
                            <td>{{ $cat->rango_inicial }} - {{ $cat->rango_final }}</td>
                            <td>{{ $cat->descripcion }}</td>
                            <td>
                                <button class="btn btn-sm text-warning btn-editar" data-id="{{ $cat->id_categoria_tarifa }}"
                                data-idclase="{{ $cat->id_clase_tarifa }}"
                                data-nombre="{{ $cat->nombre_categoria }}"
                                data-inicial="{{ $cat->rango_inicial }}"
                                data-final="{{ $cat->rango_final }}"
                                data-desc="{{ $cat->descripcion }}"
                                data-bs-toggle="modal" data-bs-target="#modalEditarCategoria">
                                <i class="las la-pen font-18"></i>
                                </button>

                                <button class="btn btn-sm text-danger btn-eliminar" data-id="{{ $cat->id_categoria_tarifa }}">
                                <i class="las la-trash-alt font-18"></i>
                                </button>
                            </td>
                            </tr>
                        @endforeach
                        </tbody>
                    </table>


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

<!-- Modal Crear -->
<div class="modal fade" id="modalCrearCategoria" tabindex="-1">
  <div class="modal-dialog">
    <form id="formCrearCategoria" class="modal-content">
      @csrf
      <div class="modal-header">
        <h5 class="modal-title">Nueva Categoría</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <div class="mb-2">
          <label class="form-label">Clase Tarifa</label>
          <select name="id_clase_tarifa" class="form-select" required>
            <option value="">Seleccione</option>
            @foreach ($clases as $c)
              <option value="{{ $c->id_clase_tarifa }}">{{ $c->nombre_clase }}</option>
            @endforeach
          </select>
        </div>
        <div class="mb-2">
          <label class="form-label">Nombre</label>
          <input type="text" name="nombre_categoria" class="form-control" required>
        </div>
        <div class="row">
          <div class="col">
            <label class="form-label">Rango Inicial (m³)</label>
            <input type="number" step="0.01" name="rango_inicial" class="form-control" required>
          </div>
          <div class="col">
            <label class="form-label">Rango Final (m³)</label>
            <input type="number" step="0.01" name="rango_final" class="form-control" required>
          </div>
        </div>
        <div class="mt-2">
          <label class="form-label">Descripción</label>
          <textarea name="descripcion" class="form-control"></textarea>
        </div>
      </div>
      <div class="modal-footer">
        <button class="btn btn-primary">Guardar</button>
        <button class="btn btn-secondary" data-bs-dismiss="modal" type="button">Cancelar</button>
      </div>
    </form>
  </div>
</div>

<!-- Modal Editar -->
<div class="modal fade" id="modalEditarCategoria" tabindex="-1">
  <div class="modal-dialog">
    <form id="formEditarCategoria" class="modal-content">
      @csrf
      @method('PUT')
      <input type="hidden" id="edit_id">
      <div class="modal-header">
        <h5 class="modal-title">Editar Categoría</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <div class="mb-2">
          <label class="form-label">Clase Tarifa</label>
          <select name="id_clase_tarifa" id="edit_id_clase" class="form-select" required>
            <option value="">Seleccione</option>
            @foreach ($clases as $c)
              <option value="{{ $c->id_clase_tarifa }}">{{ $c->nombre_clase }}</option>
            @endforeach
          </select>
        </div>
        <div class="mb-2">
          <label class="form-label">Nombre</label>
          <input type="text" name="nombre_categoria" id="edit_nombre" class="form-control" required>
        </div>
        <div class="row">
          <div class="col">
            <label class="form-label">Rango Inicial</label>
            <input type="number" step="0.01" name="rango_inicial" id="edit_inicial" class="form-control" required>
          </div>
          <div class="col">
            <label class="form-label">Rango Final</label>
            <input type="number" step="0.01" name="rango_final" id="edit_final" class="form-control" required>
          </div>
        </div>
        <div class="mt-2">
          <label class="form-label">Descripción</label>
          <textarea name="descripcion" id="edit_descripcion" class="form-control"></textarea>
        </div>
      </div>
      <div class="modal-footer">
        <button class="btn btn-warning">Actualizar</button>
        <button class="btn btn-secondary" data-bs-dismiss="modal" type="button">Cancelar</button>
      </div>
    </form>
  </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 () {
        $("#tablaSectores").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('#tablaSectores_wrapper .col-md-6:eq(0)');
    });
</script>
<!-- agregar -->
<script>
    $(function () {
    $('#formCrearCategoria').submit(function (e) {
        e.preventDefault();
        $.post("{{ route('categoria_tarifa.store') }}", $(this).serialize())
        .done(() => {
            $('#modalCrearCategoria').modal('hide');
            Swal.fire('Creado', 'Categoría registrada', 'success').then(() => location.reload());
        })
        .fail(xhr => mostrarErrores(xhr));
    });

    $('.btn-editar').click(function () {
        $('#edit_id').val($(this).data('id'));
        $('#edit_id_clase').val($(this).data('idclase'));
        $('#edit_nombre').val($(this).data('nombre'));
        $('#edit_inicial').val($(this).data('inicial'));
        $('#edit_final').val($(this).data('final'));
        $('#edit_descripcion').val($(this).data('desc'));
    });

    $('#formEditarCategoria').submit(function (e) {
        e.preventDefault();
        let id = $('#edit_id').val();
        $.ajax({
        url: `/categoria_tarifa/${id}`,
        type: 'POST',
        data: $(this).serialize(),
        success: () => {
            $('#modalEditarCategoria').modal('hide');
            Swal.fire('Actualizado', 'Categoría modificada', 'success').then(() => location.reload());
        },
        error: xhr => mostrarErrores(xhr)
        });
    });

    $('.btn-eliminar').click(function () {
        let id = $(this).data('id');
        Swal.fire({
        title: '¿Eliminar?',
        text: 'Esta acción no se puede deshacer',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Sí, eliminar',
        cancelButtonText: 'Cancelar'
        }).then(result => {
        if (result.isConfirmed) {
            $.post(`/categoria_tarifa/${id}`, {
            _method: 'DELETE',
            _token: '{{ csrf_token() }}'
            }).done(() => {
            Swal.fire('Eliminado', '', 'success').then(() => location.reload());
            }).fail(() => {
            Swal.fire('Error', 'No se pudo eliminar', 'error');
            });
        }
        });
    });

    function mostrarErrores(xhr) {
        let errores = xhr.responseJSON.errors;
        let mensaje = 'Error al guardar.';
        if (errores) {
        mensaje = Object.values(errores).map(e => `• ${e}`).join('<br>');
        }
        Swal.fire({ icon: 'error', title: 'Error', html: mensaje });
    }
    });
</script>






@endsection
