<?= $this->include("themes/_commonPartialsBs/sweetalert") ?>
<?= $this->include('themes/_commonPartialsBs/_confirm2delete') ?>
<?= $this->include('themes/_commonPartialsBs/datatables') ?>
<?= $this->include("themes/_commonPartialsBs/select2bs5") ?>
<?= $this->extend('themes/vuexy/main/defaultlayout') ?>
<?= $this->section("content") ?>
<div class="row">
    <div class="col-12">
        <div class="card card-info">
            <div class="card-header">
                <h3 class="card-title"><?= $boxTitle ?? $pageTitle ?></h3>
            </div><!--//.card-header -->
            <form id="papelImpresionForm" data-id="<?= $papelImpresion->id ?>" method="post" class="card-body" action="<?= $formAction ?>">
                <?= csrf_field() ?>
                <?= view("themes/_commonPartialsBs/_alertBoxes") ?>
                <?= !empty($validation->getErrors()) ? $validation->listErrors("bootstrap_style") : "" ?>
                <?= view("themes/vuexy/form/configuracion/papel/_papelImpresionFormItems") ?>
                <div class="pt-4">
                    <input type="submit"
                        class="btn btn-primary float-start me-sm-3 me-1"
                        name="save"
                        value="<?= lang("Basic.global.Save") ?>" />
                    <button type="button" id="btn-papel-impresion-duplicate" class="btn btn-danger me-sm-3 me-1"><i class="ti ti-xs ti-copy"></i><?= lang("Basic.global.Duplicate") ?></button>
                    <?= anchor(route_to("papelImpresionList"), lang("Basic.global.Cancel"), ["class" => "btn btn-secondary"]) ?>

                </div><!-- /.card-footer -->
            </form>
        </div><!-- //.card -->

        <?php if (str_contains($formAction, 'edit')): ?>
            <div class="accordion mt-3" id="accordionMargenes">
                <div class="card accordion-item active">
                    <h2 class="accordion-header" id="headingOne">
                        <button type="button" class="accordion-button" data-bs-toggle="collapse" data-bs-target="#accordionTip3" aria-expanded="false" aria-controls="accordionTip3">
                            <p><?= lang("PapelImpresionMargenes.accordion") ?></p>
                        </button>
                    </h2>

                    <div id="accordionTip3" class="accordion-collapse collapse show" data-bs-parent="#accordionMargenes">
                        <div class="accordion-body">

                            <table id="tableOfPapelimpresionmargenes" class="table table-striped table-hover" style="width: 100%;">
                                <thead>
                                    <tr>
                                        <th><?= lang('PapelImpresionMargenes.paginasMin') ?></th>
                                        <th><?= lang('PapelImpresionMargenes.paginasMax') ?></th>
                                        <th><?= lang('PapelImpresionMargenes.margen') ?></th>
                                        <th class="text-nowrap"><?= lang('Basic.global.Action') ?></th>
                                    </tr>
                                </thead>
                                <tbody>

                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div> <!-- //.accordion -->
        <?php endif; ?>

        <?php if (str_contains($formAction, 'edit') && ($papelImpresion->rotativa == true || $papelImpresion->inkjet == true)): ?>
            <div class="accordion mt-3" id="accordionTipologias">

                <div class="card accordion-item active">
                    <h2 class="accordion-header" id="headingOne">
                        <button type="button" class="accordion-button" data-bs-toggle="collapse" data-bs-target="#accordionTip1" aria-expanded="false" aria-controls="accordionTip1">
                            <p><?= lang("PapelImpresion.consumo_tintas_rotativas") ?></p>
                        </button>
                    </h2>

                    <div id="accordionTip1" class="accordion-collapse collapse show" data-bs-parent="#accordionTipologias">
                        <div class="accordion-body">

                            <table id="tableOfPapelimpresiontipologias" class="table table-striped table-hover" style="width: 100%;">
                                <thead>
                                    <tr>
                                        <th><?= lang('ImpresionTipologias.tipo') ?></th>
                                        <th><?= lang('ImpresionTipologias.negro') ?></th>
                                        <th><?= lang('ImpresionTipologias.cyan') ?></th>
                                        <th><?= lang('ImpresionTipologias.magenta') ?></th>
                                        <th><?= lang('ImpresionTipologias.amarillo') ?></th>
                                        <th><?= lang('ImpresionTipologias.cg') ?></th>
                                        <th><?= lang('ImpresionTipologias.gotaNegro') ?></th>
                                        <th><?= lang('ImpresionTipologias.gotaColor') ?></th>
                                        <th class="text-nowrap"><?= lang('Basic.global.Action') ?></th>
                                    </tr>
                                </thead>
                                <tbody>

                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div> <!-- //.accordion -->
        <?php endif; ?>

        <?php if (str_contains($formAction, 'edit')): ?>
            <div class="accordion mt-3" id="accordionMaquinas">

                <div class="card accordion-item">
                    <h2 class="accordion-header" id="headingTwo">
                        <button
                            type="button"
                            class="accordion-button collapsed"
                            data-bs-toggle="collapse"
                            data-bs-target="#accordionMaq"
                            aria-expanded="false"
                            aria-controls="accordionMaq">
                            <p><?= lang("PapelImpresion.maquinas_papel") ?></p>
                        </button>
                    </h2>
                    <div id="accordionMaq" class="accordion-collapse collapse" aria-labelledby="headingTwo" data-bs-parent="#accordionMaquinas">
                        <div class="accordion-body">
                            <table id="tableOfMaquinas" class="table table-striped table-hover" style="width: 100%;">
                                <thead>
                                    <tr>
                                        <th><?= lang('MaquinasPapelImpresion.activo') ?></th>
                                        <th><?= lang('Maquinas.nombre') ?></th>
                                        <th><?= lang('Maquinas.ancho') ?></th>
                                        <th><?= lang('Maquinas.alto') ?></th>
                                        <th><?= lang('Maquinas.anchoImpresion') ?></th>
                                        <th><?= lang('Maquinas.altoImpresion') ?></th>
                                        <th class="text-nowrap"><?= lang('Basic.global.Action') ?></th>
                                    </tr>
                                </thead>
                                <tbody>

                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            <?php endif; ?>
            </div><!--//.col -->
            <div class="modal fade" id="modalPapelImpresionDuplicate" tabindex="-1" aria-hidden="true">
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h3><?= lang('Basic.global.Duplicate')  ?></h3>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <div class="col-md-12">
                                <label for="duplicated_name"><?= lang("PapelImpresion.nombre") ?></label>
                                <input type="text" id="duplicated_name" name="name" class="form-control" placeholder="<?=lang("PapelImpresion.namePlaceholderDuplicated")?>">
                                <div class="invalid-feedback d-none">
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <div class="d-flex align-items-center justify-content-end gap-2">
                                <button type="button" id="btn-new-papel-impresion-duplicate" class="btn-primary btn btn-md"><?= lang('Basic.global.Save') ?></button>
                                <button type="button" class="btn-secondary btn btn-md" data-bs-dismiss="modal"><?= lang('Basic.global.Cancel') ?></button>
                            </div>

                        </div>
                    </div>
                </div>
            </div>
    </div><!--//.row -->

    <?= $this->endSection() ?>


    <?= $this->section('additionalExternalJs') ?>
    <script type="module" src="<?= site_url('assets/js/safekat/pages/configuracion/papel_impresion/duplicate.js') ?>"></script>
    <?= $this->endSection() ?>
    <!------------------------------------------->
    <!-- Código JS para  general -->
    <!------------------------------------------->
    <?= $this->section("additionalInlineJs") ?>

    var theTable;

    const url = window.location.href;
    const url_parts = url.split('/');
    let id = -1;
    if(url_parts[url_parts.length-2] == 'edit'){
    id = url_parts[url_parts.length-1];
    }

    $('#papelGenericoId').select2({

    allowClear: false,
    ajax: {
    url: '<?= route_to("menuItemsOfPapelesGenericos") ?>',
    type: 'post',
    dataType: 'json',

    data: function (params) {
    return {
    id: 'id',
    text: 'nombre',
    searchTerm: params.term,
    <?= csrf_token() ?? "token" ?> : <?= csrf_token() ?>v
    };
    },
    delay: 60,
    processResults: function (response) {

    yeniden(response.<?= csrf_token() ?>);

    return {
    results: response.menu
    };
    },

    cache: true
    }
    });


    // Delete row
    $(document).on('click', '.btn-delete', function(e) {
    $(".btn-remove").attr('data-id', $(this).attr('data-id'));
    if($(this).closest('table').attr('id').includes('margenes')){
    $(".btn-remove").attr('table', "margenes");
    }
    else if($(this).closest('table').attr('id').includes('tipologias')){
    $(".btn-remove").attr('table', "tipologias");
    }
    else{
    $(".btn-remove").attr('table', );
    }
    });

    $(document).on('click', '.btn-remove', function(e) {
    const dataId = $(this).attr('data-id');
    const row = $(this).closest('tr');
    if ($.isNumeric(dataId)) {

    if($(this).attr('table').includes('margenes')){
    remove_margenes(dataId, row);
    }
    else if ($(this).attr('table').includes('tipologias')){
    remove_tipologias(dataId, row);
    }
    }
    });
    <?= $this->endSection() ?>




    <?php if (str_contains($formAction, 'edit')): ?>


        <!------------------------------------------->
        <!-- Código JS para tabla margenes -->
        <!------------------------------------------->
        <?= $this->section("additionalInlineJs") ?>

        var theTable3;
        const lastColNr3 = $('#tableOfPapelimpresionmargenes').find("tr:first th").length - 1;
        const actionBtns3 = function(data) {
        return `
        <span class="edit"><a href="javascript:void(0);"><i class="ti ti-pencil ti-sm btn-edit3 mx-2" data-id="${data.id}"></i></a></span>
        <a href="javascript:void(0);"><i class="ti ti-trash ti-sm btn-delete mx-2" data-id="${data.id}" data-bs-toggle="modal" data-bs-target="#confirm2delete"></i></a>
        <span class="cancel"></span>
        `;
        };


        // Definición del editor
        var editor3 = new $.fn.dataTable.Editor( {
        ajax: {
        url: "<?= route_to('editorOfPapelImpresionMargenes') ?>",
        headers: {
        <?= csrf_token() ?? "token" ?> : <?= csrf_token() ?>v,
        },
        },
        table : "#tableOfPapelimpresionmargenes",
        idSrc: 'id',
        fields: [
        {
        name: "paginas_min",
        attr: {
        type: "text",
        name : "paginas_min",
        class :"autonumeric"
        }
        },{
        name: "paginas_max",
        attr: {
        type: "text",
        name : "paginas_max",
        class :"autonumeric"
        }
        },{
        name: "margen",
        attr: {
        type: "text",
        name : "margen",
        class :"autonumeric"
        }
        }, {
        "name": "papel_impresion_id",
        "type": "hidden"
        }, {
        "name": "deleted_at",
        "type": "hidden"
        }, {
        "name": "is_deleted",
        "type": "hidden"
        },
        ]
        } );


        editor3.on('open',(event)=>{
            $("input.autonumeric").each(function () {
                let autoNumericInstance = AutoNumeric.getAutoNumericElement(this)
                if(autoNumericInstance){
                    autoNumericInstance.remove()

                }
                new AutoNumeric(this, {
                        decimalCharacter: ",",
                        digitGroupSeparator: ".",
                        unformatOnSubmit : true,
                    });
            })
        })

        // Definición de la tabla
        theTable3 = $('#tableOfPapelimpresionmargenes').DataTable({
        processing: true,
        serverSide: true,
        autoWidth: true,
        responsive: true,
        scrollX: true,
        lengthMenu: [ 5],
        pageLength: 5,
        lengthChange: false,
        searching: false,
        info: false,
        dom: '<"mt-4"><"float-end"B><"float-start"l><t><"mt-4 mb-3"p>',


                            stateSave: true,
                            language: {
                            url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json"
                            },
                            ajax : $.fn.dataTable.pipeline( {
                            url: '<?= route_to('dataTableOfPapelImpresionMargen') ?>',
                            data: {
                            id_PI: id,
                            },
                            method: 'POST',
                            headers: {'X-Requested-With': 'XMLHttpRequest'},
                            async: true,
                            }),
                            columns : [
                            { 'data': 'paginas_min' , render : (d) => `<span class="autonumeric">${d}</span>` },
                            { 'data': 'paginas_max' , render : (d) => `<span class="autonumeric">${d}</span>`},
                            { 'data': 'margen', render : (d) => `<span class="autonumeric">${d}</span>`},
                            { data: actionBtns3,
                            className: 'row-edit dt-center'}
                            ],
                            columnDefs: [
              
                            {
                            orderable: false,
                            searchable: false,
                            targets: [lastColNr3]
                            }
                            ],
                            buttons: [ {
                            className: 'btn btn-primary float-end me-sm-3 me-1',
                            extend: "createInline",
                            editor: editor3,
                            formOptions: {
                            submitTrigger: -1,
                            submitHtml: '<a href="javascript:void(0);"><i class="ti ti-device-floppy"></i></a>'
                            }
                            } ]
                            });

  
                            // Activate an inline edit on click of a table cell
                            $(document).on('click', '.btn-edit3', function(e) {
                            editor3.inline(
                            theTable3.cells(this.parentNode.parentNode.parentNode, '*').nodes(),
                            {
                            cancelHtml: '<a href="javascript:void(0);"><i class="ti ti-x"></i></a>',
                            cancelTrigger: 'span.cancel',
                            submitHtml: '<a href="javascript:void(0);"><i class="ti ti-device-floppy"></i></a>',
                            submitTrigger: 'span.edit',
                            submit: 'allIfChanged'
                            }
                            );
                            } );

                  
                            // Obtención del id para editar
                            editor3.on( 'preSubmit', function ( e, d, type ) {
                                if (d.data) {
                                    Object.keys(d.data).forEach(function (key) {
                                        // Find all elements with class .autonumeric
                                        $("input.autonumeric").each(function () {
                                            let autoNumericInstance = AutoNumeric.getAutoNumericElement(this)
                                                if (autoNumericInstance) {
                                                    // Get raw value and update the corresponding field
                                                    let rawValue = autoNumericInstance.getNumericString();
                                                    d.data[key][this.name] = rawValue; // Ensure the correct name attribute is used
                                                }
                                        });
                                    });
                                }
                            if ( type === 'create'){
                            d.data[0]['papel_impresion_id'] = id;
                            }
                            else if(type === 'edit' ) {
                            for (v in d.data){
                            d.data[v]['papel_impresion_id'] = id;
                            }
                            }
                            });

                            // Refrescar token
                            editor3.on( 'postSubmit', function ( e, json, data, action ) {

                            yeniden(json.<?= csrf_token() ?>);
                            });

                            // Refrescar tabla
                            editor3.on( 'submitSuccess', function ( e, json, data, action ) {

                            theTable3.clearPipeline();
                            theTable3.draw();
                            });


                            // Delete row
                            function remove_margenes(dataId, row){

                            $.ajax({
                            url: `/configuracion/papelimpresionmargenes/delete/${dataId}`,
                            method: 'GET',
                            }).done((data, textStatus, jqXHR) => {
                            $('#confirm2delete').modal('toggle');
                            theTable3.clearPipeline();
                            theTable3.row($(row)).invalidate().draw();
                            popSuccessAlert(data.msg ?? jqXHR.statusText);
                            }).fail((jqXHR, textStatus, errorThrown) => {
                            popErrorAlert(jqXHR.responseJSON.messages.error)
                            });
                            }


                            <?= $this->endSection() ?>

                            <!------------------------------------------->
                            <!-- Código JS para tabla tipologias -->
                            <!------------------------------------------->
                            <?= $this->section("additionalInlineJs") ?>

                            var theTable;
                            const lastColNr = $('#tableOfPapelimpresiontipologias').find("tr:first th").length - 1;
                            const actionBtns = function(data) {
                            return `
                            <span class="edit"><a href="javascript:void(0);"><i class="ti ti-pencil ti-sm btn-edit mx-2" data-id="${data.id}"></i></a></span>
                            <a href="javascript:void(0);"><i class="ti ti-trash ti-sm btn-delete mx-2" data-id="${data.id}" data-bs-toggle="modal" data-bs-target="#confirm2delete"></i></a>
                            <span class="cancel"></span>
                            `;
                            };

                            $('#cubierta').on('change', function() {
                            if($(this).is(':checked')) {
                            $('#useForTapaDura').prop('disabled', false);
                            $('#useForTapaDura').prop('checked', false);
                            }
                            else{
                            $('#useForTapaDura').prop('disabled', true);
                            }
                            });


                            // Etiquetas para las tipologias
                            const tipoTypes = [
                            {label:'<?= lang('ImpresionTipologias.negro') ?>', value:'negro'},
                            {label:'<?= lang('ImpresionTipologias.color') ?>', value: 'color'},
                            {label:'<?= lang('ImpresionTipologias.bicolor') ?>', value: 'bicolor'}
                            ];


                            // Definición del editor
                            editor = new $.fn.dataTable.Editor( {
                            ajax: {
                            url: "<?= route_to('editorOfConsumoTintas') ?>",
                            headers: {
                            <?= csrf_token() ?? "token" ?> : <?= csrf_token() ?>v,
                            },
                            },
                            table : "#tableOfPapelimpresiontipologias",
                            idSrc: 'id',
                            fields: [
                            {
                            name: "tipo",
                            type: "select",
                            options: tipoTypes
                            }, {
                            name: "negro",
                            attr: {
                                type: "text",
                                name : "negro",
                                class :"autonumeric"
                            }
                            },{
                            name: "cyan",
                            attr: {
                                type: "text",
                                name : "cyan",
                                class :"autonumeric"
                            }
                            },{
                            name: "magenta",
                            attr: {
                                type: "text",
                                name : "magenta",
                                class :"autonumeric"
                            }
                            },{
                            name: "amarillo",
                            attr: {
                                type: "text",
                                name : "amarillo",
                                class :"autonumeric"
                            }
                            },{
                            name: "cg",
                            attr: {
                                type: "text",
                                name : "cg",
                                class :"autonumeric"
                            },
                            def: 0,
                            },
                            {
                            name: "gota_negro",
                            attr: {
                                type: "text",
                                name : "gota_negro",
                                class :"autonumeric"
                            }
                            },{
                            name: "gota_color",
                            attr: {
                                type: "text",
                                name : "gota_color",
                                class :"autonumeric"
                            }
                            }, {
                            "name": "papel_impresion_id",
                            "type": "hidden"
                            }
                            ]
                            } );


                            // Definición de la tabla
                            theTable = $('#tableOfPapelimpresiontipologias').DataTable({
                            processing: true,
                            serverSide: true,
                            autoWidth: true,
                            responsive: true,
                            scrollX: true,
                            lengthMenu: [ 5],
                            pageLength: 5,
                            lengthChange: false,
                            searching: false,
                            info: false,
                            dom: '<"mt-4"><"float-end"B><"float-start"l><t><"mt-4 mb-3"p>',


                                                stateSave: true,
                                                language: {
                                                url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json"
                                                },
                                                ajax : $.fn.dataTable.pipeline( {
                                                url: '<?= route_to('dataTableOfPapelesImpresion') ?>',
                                                data: {
                                                id_PI: id,
                                                },
                                                method: 'POST',
                                                headers: {'X-Requested-With': 'XMLHttpRequest'},
                                                async: true,
                                                }),
                                                columns : [
                                                { 'data': 'tipo', "render": function ( data, type, row, meta ) {
                                                if(data=='negro')
                                                return '<?= lang('ImpresionTipologias.negro') ?>';
                                                else if (data=='color')
                                                return '<?= lang('ImpresionTipologias.color') ?>';
                                                else if (data=='bicolor')
                                                return '<?= lang('ImpresionTipologias.bicolor') ?>';
                                                }
                                                },
                                                { 'data': 'negro',render : (d) => `<span class="autonumeric">${d}</span>` },
                                                { 'data': 'cyan',render : (d) => `<span class="autonumeric">${d}</span>` },
                                                { 'data': 'magenta',render : (d) => `<span class="autonumeric">${d}</span>` },
                                                { 'data': 'amarillo',render : (d) => `<span class="autonumeric">${d}</span>` },
                                                { 'data': 'cg',render : (d) => `<span class="autonumeric">${d}</span>` },
                                                { 'data': 'gota_negro',render : (d) => `<span class="autonumeric">${d}</span>` },
                                                { 'data': 'gota_color',render : (d) => `<span class="autonumeric">${d}</span>` },
                                                { data: actionBtns,
                                                className: 'row-edit dt-center'}
                                                ],
                                                columnDefs: [
                                                {
                                                visible: false,
                                                targets: [5]
                                                }
                                                ],
                                                buttons: [ {
                                                className: 'btn btn-primary float-end me-sm-3 me-1',
                                                extend: "createInline",
                                                editor: editor,
                                                formOptions: {
                                                submitTrigger: -1,
                                                submitHtml: '<a href="javascript:void(0);"><i class="ti ti-device-floppy"></i></a>'
                                                }
                                                } ],
                                                initComplete: function () {
                                                <?php if ($papelImpresion->inkjet) { ?>
                                                    theTable.column(5).visible(true)
                                                <?php } ?>
                                                }
                                                });
                                                editor.on('open', (event) => {
                                                    $("input.autonumeric").each(function () {
                                                        let autoNumericInstance = AutoNumeric.getAutoNumericElement(this)
                                                        if (autoNumericInstance) {
                                                            autoNumericInstance.remove()

                                                        }
                                                        new AutoNumeric(this, {
                                                            decimalCharacter: ",",
                                                            digitGroupSeparator: ".",
                                                            allowDecimalPadding : 'floats',
                                                            decimalPlaces: 2,
                                                            unformatOnSubmit: true,
                                                        });
                                                    })
                                                })

                                                // Notificar que no se pueden añadir más tipologías
                                                editor.on( 'initCreate', function () {
                                                if ( $('#tableOfPapelimpresiontipologias').DataTable().data().count() >= 3 ){
                                                editor.close();
                                                popErrorAlert('<?= lang('Basic.global.sweet.maxRowsReached') ?>');
                                                }
                                                });


                                                // Activate an inline edit on click of a table cell
                                                $(document).on('click', '.btn-edit', function(e) {
                                                editor.inline(
                                                theTable.cells(this.parentNode.parentNode.parentNode, '*').nodes(),
                                                {
                                                cancelHtml: '<a href="javascript:void(0);"><i class="ti ti-x"></i></a>',
                                                cancelTrigger: 'span.cancel',
                                                submitHtml: '<a href="javascript:void(0);"><i class="ti ti-device-floppy"></i></a>',
                                                submitTrigger: 'span.edit',
                                                submit: 'allIfChanged'
                                                }
                                                );
                                                } );


                                                // Obtención del id para editar
                                                editor.on( 'preSubmit', function ( e, d, type ) {
                                                    if (d.data) {
                                                        Object.keys(d.data).forEach(function (key) {
                                                            // Find all elements with class .autonumeric
                                                            $("input.autonumeric").each(function () {
                                                                let autoNumericInstance = AutoNumeric.getAutoNumericElement(this)
                                                                if (autoNumericInstance) {
                                                                    // Get raw value and update the corresponding field
                                                                    let rawValue = autoNumericInstance.getNumericString();
                                                                    d.data[key][this.name] = rawValue; // Ensure the correct name attribute is used
                                                                }
                                                            });
                                                        });
                                                    }
                                                if ( type === 'create'){
                                                d.data[0]['papel_impresion_id'] = id;
                                                }
                                                else if(type === 'edit' ) {
                                                for (v in d.data){
                                                d.data[v]['papel_impresion_id'] = id;
                                                }
                                                }
                                                });

                                                // Refrescar token
                                                editor.on( 'postSubmit', function ( e, json, data, action ) {

                                                yeniden(json.<?= csrf_token() ?>);
                                                });

                                                // Refrescar tabla
                                                editor.on( 'submitSuccess', function ( e, json, data, action ) {

                                                theTable.clearPipeline();
                                                theTable.draw();
                                                });


                                                // Delete row
                                                function remove_tipologias(dataId, row){

                                                $.ajax({
                                                url: `/configuracion/papelimpresiontipologias/delete/${dataId}`,
                                                method: 'GET',
                                                }).done((data, textStatus, jqXHR) => {
                                                $('#confirm2delete').modal('toggle');
                                                theTable.clearPipeline();
                                                theTable.row($(row)).invalidate().draw();
                                                popSuccessAlert(data.msg ?? jqXHR.statusText);
                                                }).fail((jqXHR, textStatus, errorThrown) => {
                                                popErrorAlert(jqXHR.responseJSON.messages.error)
                                                });
                                                }

                                                <?= $this->endSection() ?>


                                                <!------------------------------------------->
                                                <!-- Código JS para tabla maquinas -->
                                                <!------------------------------------------->
                                                <?= $this->section("additionalInlineJs") ?>

                                                // Botones última columna
                                                const lastColNr2 = $('#tableOfMaquinas').find("tr:first th").length - 1;
                                                const actionBtns2 = function(data) {
                                                return `
                                                <a href="javascript:void(0);"><i class="ti ti-pencil ti-sm btn-edit2 mx-2" data-id="${data.maquina_id}"></i></a>
                                                `;
                                                };


                                                // Definicion de la tabla
                                                var theTable2 = $('#tableOfMaquinas').DataTable( {
                                                serverSide: true,
                                                processing: true,
                                                autoWidth: true,
                                                responsive: true,
                                                lengthMenu: [ 5, 10, 25],
                                                order: [[ 1, "asc" ]],
                                                pageLength: 10,
                                                lengthChange: true,
                                                searching: true,
                                                paging: true,
                                                info: true,
                                                dom: "lftp",
                                                ajax : $.fn.dataTable.pipeline( {
                                                url: '<?= route_to('dataTableOfPapelesImpresionMaquinas') ?>',
                                                data: function (d) {
                                                d.papel_id = id;
                                                d.isRotativa = $('#rotativa').is(':checked')?1:0;
                                                d.webguard_token = '<?= csrf_hash() ?>';
                                                },
                                                method: 'POST',
                                                headers: {'X-Requested-With': 'XMLHttpRequest'},
                                                async: true,
                                                }),
                                                columns: [
                                                { 'data': 'active',
                                                render: function (data, type, row) {
                                                if (type === 'display') {
                                                return '<input type="checkbox" class="editor-active" id="check_' + row.papel_impresion_id + '">';
                                                }
                                                return data;
                                                },
                                                className: 'dt-body-center'
                                                },
                                                { 'data': 'maquina'},
                                                { 'data': 'ancho',render : (d) => `<span class="autonumeric">${d}</span>`},
                                                { 'data': 'alto',render : (d) => `<span class="autonumeric">${d}</span>`},
                                                { 'data': 'anchoimpresion',render : (d) => `<span class="autonumeric">${d}</span>`},
                                                { 'data': 'altoimpresion',render : (d) => `<span class="autonumeric">${d}</span>`},
                                                { data: actionBtns2,
                                                className: 'row-edit dt-center'}
                                                ],
                                                columnDefs: [
                                                {
                                                orderable: false,
                                                searchable: false,
                                                targets: [lastColNr2]
                                                }
                                                ],
                                                rowCallback: function (row, data) {
                                                // Set the checked state of the checkbox in the table
                                                $('input.editor-active', row).prop('checked', data.active == 1);
                                                },
                                                language: {
                                                url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json"
                                                },
                                                columnDefs: [
                                                {
                                                searchable: false,
                                                targets: [0,2,3,4,5]
                                                }
                                                ],
                                                } );


                                                // Definición del editor
                                                editor2 = new $.fn.dataTable.Editor( {
                                                ajax: {
                                                url: "<?= route_to('editorOfMaquinasPapelImpresion') ?>",
                                                headers: {
                                                <?= csrf_token() ?? "token" ?> : <?= csrf_token() ?>v,
                                                },
                                                },
                                                table : "#tableOfMaquinas",
                                                idSrc: 'papel_impresion_id',
                                                fields: [
                                                {
                                                name: "active",
                                                type: "checkbox",
                                                separator: "|",
                                                ipOpts: [
                                                { label: '', value: 1 }
                                                ]
                                                },{
                                                "name": "papel_impresion_id",
                                                "type": "hidden"
                                                },{
                                                "name": "gramaje",
                                                "type": "hidden"
                                                },{
                                                "name": "maquina_id",
                                                "type": "hidden"
                                                }
                                                ]
                                                } );


                                                // Postsubmit del editor
                                                editor2.on( 'postSubmit', function ( e, json, data, action ) {
                                                yeniden(json.<?= csrf_token() ?>);
                                                if(json.error){
                                                document.getElementById("check_" + json.data.papel_impresion_id).checked = false;
                                                popErrorAlert(json.error);
                                                }
                                                });


                                                // Click sobre el botón editar máquina
                                                $(document).on('click', '.btn-edit2', function(e) {
                                                window.open(`/configuracion/maquinas/edit/${$(this).attr('data-id')}`);
                                                });


                                                // Cuando se clica en un checkbox hacer submit en el editor
                                                theTable2.on( 'change', 'input.editor-active', function () {
                                                editor2
                                                .edit( $(this).closest('tr'), false )
                                                .set( 'active', $(this).prop( 'checked' ) ? 1 : 0 )
                                                .submit();
                                                } );

                                                $('#rotativa').on('change', function() {
                                                if($('#inkjet').prop('checked')){
                                                $('#inkjet').prop('checked', false)
                                                }
                                                })

                                                $('#inkjet').on('change', function() {
                                                if($('#rotativa').prop('checked')){
                                                $('#rotativa').prop('checked', false)
                                                }
                                                })

                                                <?= $this->endSection() ?>

                                            <?php endif; ?>


                                            <?= $this->section('css') ?>
                                            <link rel="stylesheet" href="<?= site_url('themes/vuexy/css/datatables-editor/editor.dataTables.min.css') ?>">
                                            <link rel="stylesheet" href="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/buttons.bootstrap5.min.css") ?>">
                                            <?= $this->endSection() ?>

                                            <?= $this->section('additionalExternalJs') ?>
                                            <script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/dataTables.buttons.min.js") ?>"></script>
                                            <script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/buttons.bootstrap5.min.js") ?>"></script>
                                            <script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/buttons.html5.min.js") ?>"></script>
                                            <script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/buttons.print.min.js") ?>"></script>
                                            <script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/jszip/jszip.min.js") ?>"></script>
                                            <script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/pdfmake/pdfmake.min.js") ?>" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
                                            <script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/pdfmake/vfs_fonts.js") ?>"></script>
                                            <script src="<?= site_url('themes/vuexy/js/datatables-editor/dataTables.editor.min.js') ?>"></script>

                                            <?= $this->endSection() ?>