$(document).ready(function() {
    // Eliminar instancia previa de DataTable si existe
    if ($.fn.DataTable.isDataTable("#table_historial")) {
        $("#table_historial").DataTable().destroy();
    }

    let table = $("#table_historial").DataTable({
        "deferRender": true,   
        "paging": false,       
        "lengthChange": false, 
        "searching": true,     
        "processing": true,    
        "scrollY": false,    
        "scrollCollapse": true,
        "dom": 'Bfrtip',
        "buttons": [
            {
                extend: 'excelHtml5',
                text: '<i class="fas fa-file-excel info"></i>',
                className: 'btn-excel'
            }
        ],
        "ajax": {
            "url": "funcion_historial.php",
            "type": "POST",
            "cache": false,
            "data": function(d) {
                d.cifras = $("#cifras").val(); 
                d.timestamp = new Date().getTime();
            }
        },
        "columns": [
            { "data": "cifras", className: "text-center"},
            { "data": "codigo", className: "text-end"},
            { "data": "loteria", className: "text-center"},
            { "data": "numero", className: "text-end"},
            { "data": "fechar", className: "text-end"},
            { "data": "fechaj", className: "text-end"},
            { "data": "valor", className: "text-end"},
            { "data": "negocio", className: "text-center"},
            { "data": "usuario", className: "text-center"},          
            { "data": "pagar", className: "text-end"}
        ],
        "language": {
            "processing": "Procesando...",
            "zeroRecords": "No se encontraron resultados",
            "emptyTable": "Ningún dato disponible en esta tabla",
            "info": "Mostrando _START_ a _END_ de _TOTAL_ registros",
            "infoEmpty": "Mostrando 0 a 0 de 0 registros",
            "infoFiltered": "(filtrado de _MAX_ registros)",
            "loadingRecords": "Por favor espere - cargando...",
            "search": "Buscar:",  
            "paginate": {
                "first": "Primero",
                "last": "Último",
                "next": "Siguiente",
                "previous": "Anterior"
            }
        }
    });

    // Ajustar tamaño de la caja de búsqueda dinámicamente
    $(".dataTables_filter input").css({
        "width": "100%",
        "max-width": "300px",
        "display": "inline-block",
        "padding": "6px",
        "font-size": "14px"
    });

    // Recargar datos cada 30s si hay cambios
    setInterval(function() {
        table.ajax.reload(null, false);
    }, 30000);
});
