import Ajax from '../../components/ajax.js';

document.addEventListener('DOMContentLoaded', function () {

    const lastColNr = $('#tableOfCatalogoLibros').find("tr:first th").length - 1;

    const theTable = $('#tableOfCatalogoLibros').DataTable({
        processing: true,
        serverSide: true,
        autoWidth: true,
        orderCellsTop: true,
        responsive: true,
        scrollX: true,
        lengthMenu: [5, 10, 25, 50, 75, 100, 250, 500, 1000, 2500],
        pageLength: 10,
        lengthChange: true,
        dom: 'lfBrtip',
        buttons: [
            'copy', 'csv', 'excel', 'print', {
                extend: 'pdfHtml5',
                orientation: 'landscape',
                pageSize: 'A4'
            }
        ],
        order: [[1, 'asc']],
        language: {
            url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json"
        },
        ajax: {
            url: '/catalogo/libros/datatable',
            method: 'GET'
        },
        columnDefs: [
            {
                orderable: false,
                searchable: false,
                targets: [lastColNr]
            }
        ],
        columns: [
            { data: 'portada' },
            { data: 'id' },
            { data: 'titulo' },
            { data: 'cliente' },
            {
                data: 'edicion',
                className: "text-center"
            },
            { data: 'autor' },
            { data: 'isbn' },
            { data: 'ean' },
            {
                data: 'paginas',
                className: "text-center"
            },
            { data: 'actionBtns' }
        ]
    });

    $(document).on('click', '.btn-edit', function (e) {
        window.location.href = '/catalogo/libros/edit/' + $(this).attr('data-id');
    });

    $(document).on('click', '.btn-delete', function (e) {
        e.preventDefault();
        const row = $(this).closest('tr')[0]._DT_RowIndex;
        const dataId = $(this).attr('data-id');

        Swal.fire({
            title: '¿Estás seguro?',
            text: 'Esta acción no se puede deshacer.',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Sí',
            cancelButtonText: 'No',
            reverseButtons: false,
            buttonsStyling: true,
            customClass: {
                confirmButton: 'btn btn-danger',   // rojo para "Sí"
                cancelButton: 'btn btn-secondary'  // gris para "No"
            }
        }).then((result) => {
            if (result.isConfirmed) {
                new Ajax(
                    '/catalogo/libros/delete/' + dataId,
                    {},
                    {},
                    (data, textStatus, jqXHR) => {
                        theTable.clearPipeline();
                        theTable.row($(row)).invalidate().draw();

                        popSuccessAlert(data.msg ?? jqXHR.statusText);
                    },
                    (error) => {
                        console.error(error);
                        Swal.fire('Error', 'No se pudo eliminar el libro.', 'error');
                    }
                ).get();
            }
        });

    });


    $(document).on("keyup", ".filtro_catalogo", (event) => {
        let columnName = $(event.currentTarget).attr("name");
        let columnIndex = $('#tableOfCatalogoLibros').DataTable().columns().eq(0).filter(function (index) {
            return $('#tableOfCatalogoLibros').DataTable().column(index).dataSrc() === columnName;
        })[0];
        $('#tableOfCatalogoLibros').DataTable().column(columnIndex).search($(event.currentTarget).val()).draw()
    })


});
