<?= $this->include("themes/_commonPartialsBs/datatables") ?>
<?= $this->include("themes/_commonPartialsBs/select2bs5") ?>
<?= $this->include("themes/_commonPartialsBs/sweetalert") ?>
<?= $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="maquinaForm" class="card-body" method="post" action="<?= $formAction ?>" data-id="<?= $maquina->id ?>">
				<?= csrf_field() ?>
                <div class="card-body">
                    <?= view("themes/_commonPartialsBs/_alertBoxes") ?>
                    <?= !empty($validation->getErrors()) ? $validation->listErrors("bootstrap_style") : "" ?>
                    <?= view("themes/vuexy/form/configuracion/maquinas/_maquinaFormItems") ?>
                </div><!-- /.card-body -->
                <div class="py-4">
                    <input type="submit"
                    class="btn btn-primary  me-sm-3 me-1"
                    name="save"
                    value="<?= lang("Basic.global.Save") ?>"
                    />
                    <button type="button" id="btn-maquina-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("maquinaList"), lang("Basic.global.Cancel"), ["class" => "btn btn-secondary"]) ?>
                </div><!-- /.card-footer -->
                <div class="modal fade" id="modalMaquinaDuplicate" 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("Maquinas.nombre") ?></label>
                                <input type="text" id="duplicated_name" name="name" class="form-control" placeholder="<?=lang("Maquinas.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-maquina-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>
			</form>
    </div><!-- //.card -->
    </div><!--//.col -->
</div><!--//.row -->


<?php if(str_contains($formAction,'edit')): ?>
        
    <div class="accordion mt-3" id="accordianTarifasImpresion">
        <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">
                    <h3><?= lang("MaquinasTarifasImpresions.moduleTitle") ?></h3>
                </button>
            </h2>

            <div id="accordionTip1" class="accordion-collapse collapse show" data-bs-parent="#accordianTarifasImpresion">
                <div class="accordion-body">
                    
                    <table id="tableOfMaquinastarifasimpresion" class="table table-striped table-hover" style="width: 100%;">
                        <thead>
                            <tr>
                                <th><?= lang('MaquinasTarifasImpresions.uso') ?></th>
                                <th><?= lang('MaquinasTarifasImpresions.tipo') ?></th>
                                <th><?= lang('MaquinasTarifasImpresions.precio') ?></th>
                                <th><?= lang('MaquinasTarifasImpresions.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')): ?>
    
    <div class="accordion mt-3" id="accordianPapelesCalles">
        <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">
                    <h3><?= lang("MaquinasCalles.moduleTitle") ?></h3>
                </button>
            </h2>

            <div id="accordionTip3" class="accordion-collapse collapse show" data-bs-parent="#accordianPapelesCalles">
                <div class="accordion-body">
                    <table id="tableOfCalles" class="table table-striped table-hover" style="width: 100%;">
                        <thead>
                            <tr>
                                <th><?= lang('MaquinasCalles.formas') ?></th>
                                <th><?= lang('MaquinasCalles.internas') ?></th>
                                <th><?= lang('MaquinasCalles.externas') ?></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="accordianPapelesImpresion">
        <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="#accordionTip2" aria-expanded="false" aria-controls="accordionTip2">
                    <h3><?= lang("MaquinasPapelImpresion.papel_impresion_maquinas") ?></h3>
                </button>
            </h2>

            <div id="accordionTip2" class="accordion-collapse collapse show" data-bs-parent="#accordianPapelesImpresion">
                <div class="accordion-body">
                    <div class="row table-responsive">
                        <table id="tableOfPapelesImpresion" class="table table-striped table-hover" style="width: 100%;">
                            <thead>
                                <tr>
                                    <th><?= lang('MaquinasPapelImpresion.activo') ?></th>
                                    <th><?= lang('PapelGenerico.papelGenerico') ?></th>
                                    <th><?= lang('PapelImpresion.nombre') ?></th>
                                    <th><?= lang('PapelImpresion.gramaje') ?></th>
                                    <th><?= lang('PapelImpresion.bn') ?></th>
                                    <th><?= lang('PapelImpresion.color') ?></th>
                                    <th><?= lang('PapelImpresion.cubierta') ?></th>
                                    <th><?= lang('PapelImpresion.sobrecubierta') ?></th>
                                    <th><?= lang('PapelImpresion.rotativa') ?></th>
                                    <th class="text-nowrap"><?= lang('Basic.global.Action') ?></th>
                                </tr>
                            </thead>
                            <tbody>
                            </tbody>
                        </table>   
                    </div>
                </div>
            </div>
        </div>
    </div> <!-- //.accordion -->

    <?= view("themes/_commonPartialsBs/_modalConfirmDialog") ?>

<?php endif; ?>





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





<?= $this->section("additionalInlineJs") ?>


    <?php if($maquina->is_rotativa) { ?> 
        $(".datosInkjet").css('display', 'none');
        $(".datosRotativa").css('display', 'inline');
    <?php } ?> 
    <?php if($maquina->is_inkjet) { ?> 
        $(".datosRotativa").css('display', 'none');
        $(".datosInkjet").css('display', 'inline');
    <?php } ?> 
    <?php if(!$maquina->is_inkjet && !$maquina->is_rotativa){ ?> 
        $(".datosRotativa").css('display', 'none');
        $(".datosInkjet").css('display', 'none');
    <?php } ?> 

    const lastColNr2 = $('#tableOfPapelesImpresion').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.papel_impresion_id}"></i></a>
                `;
    };

    $(document).on('click', '.btn-edit2', function(e) {
        window.open(`/configuracion/papelesimpresion/edit/${$(this).attr('data-id')}`); 
    });

    function watch(j) {
        return new Proxy(JSON.parse ('{"watch":' + j + '}'), {
            set: function(target, property, value) {
                target[property] = value;
                $('#tableOfPapelesImpresion').DataTable().ajax.reload(null,false);
                theTable2.clearPipeline();    
                theTable2.draw();
                
            }
        });
    }
    
    isRotativa = watch(0);
    

    $('#isRotativa').on("click",function(el){
        asyncConfirmDialog('<?= lang('MaquinasPapelImpresion.sureToChangeRotativaTitle') ?>',
                '<?= lang('MaquinasPapelImpresion.sureToChangeRotativaText') ?>', yesCallback, noCallback);
    });

    function yesCallback() {
        if($('#isRotativa').is(':checked')){
            $(".datosInkjet").css('display', 'none');
            $('#isTinta').prop("checked", 0);
            $(".datosRotativa").css('display', 'inline');
        }else{
            document.getElementById("precioTintaNegro").value = 0;
            document.getElementById("precioTintaColor").value = 0;
            document.getElementById("velocidadCorte").value = 0;
            document.getElementById("precioHoraCorte").value = 0;
            document.getElementById("metrosxminuto").value = 0;
            $(".datosRotativa").css('display', 'none');
        }

        updatePapeles()
    }

    function noCallback() {
        // Toggle behaviour
        $('#isRotativa').prop("checked", !$('#isRotativa').prop("checked"));
    }

    
    $('#isTinta').on('click', function(){
        asyncConfirmDialog('<?= lang('MaquinasPapelImpresion.sureToChangeRotativaTitle') ?>',
                '<?= lang('MaquinasPapelImpresion.sureToChangeRotativaText') ?>', yesCallbackInkjet, noCallbackInkjet);
        
    })

    function yesCallbackInkjet() {
        if($('#isTinta').is(':checked')){
            $(".datosRotativa").css('display', 'none');
            $(".datosInkjet").css('display', 'inline');
            $('#isRotativa').prop("checked", 0);
        }else{
            document.getElementById("precioTintaNegro").value = 0;
            document.getElementById("precioTintaColor").value = 0;
            document.getElementById("velocidadCorte").value = 0;
            document.getElementById("precioHoraCorte").value = 0;
            document.getElementById("metrosxminuto").value = 0;
            $(".datosInkjet").css('display', 'inline');
        }
        updatePapeles()
    }

    function noCallbackInkjet() {
        // Toggle behaviour
        $('#isTinta').prop("checked", !$('#isTinta').prop("checked"));
    }



    function updatePapeles(){
        //yeniden(json.<?= csrf_token() ?>);

        $.ajax({
            url: '<?= route_to('updateMaquinaPapelOnTarifasChange') ?>',
            data: {
                maquina_id: id,
                isRotativa: ()=>{ return $('#isRotativa').prop('checked')?1:0},
                isInkjet: $('#isTinta').prop('checked'),
                <?= csrf_token() ?? "token" ?>: <?= csrf_token() ?>v,
            },
            method: 'POST',
            headers: {'X-Requested-With': 'XMLHttpRequest'},
            success:function(response){
                
                token=JSON.parse(response).<?= csrf_token() ?>;
                yeniden(token);

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

    $('#isPadre').on("click",function(el){
        if($(this).is(':checked')){
            $("#selectVariante").show();
        }else{
            $("#padreId").select2('val', -1);
            $("#selectVariante").hide();
        }
    });

    $('#padreId').select2({
        allowClear: false,
        ajax: {
            url: '<?= route_to("menuItemsOfMaquinas") ?>',
            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
        },
        
    });

    const lastColNr = $('#tableOfTarifamanipuladolineas').find("tr:first th").length - 1;
    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];
    }

    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>
                `;
    };


    usoTypes = [
        {label:'<?= lang('MaquinasTarifasImpresions.interior') ?>', value:'interior'}, 
        {label:'<?= lang('MaquinasTarifasImpresions.cubierta') ?>', value: 'cubierta'},
        {label:'<?= lang('MaquinasTarifasImpresions.sobrecubierta') ?>', value: 'sobrecubierta'}
    ];
    
    tipoTypes = [
        {label:'<?= lang('MaquinasTarifasImpresions.negro') ?>', value:'negro'}, 
        {label:'<?= lang('MaquinasTarifasImpresions.negrohq') ?>', value: 'negrohq'},
        {label:'<?= lang('MaquinasTarifasImpresions.bicolor') ?>', value: 'bicolor'},
        {label:'<?= lang('MaquinasTarifasImpresions.color') ?>', value: 'color'},
        {label:'<?= lang('MaquinasTarifasImpresions.colorhq') ?>', value: 'colorhq'},
    ];

	editor = new $.fn.dataTable.Editor( {
        ajax: {
            url: "<?= route_to('editorOfMaquinasTarifaImpresion') ?>", 
            headers: {
                <?= csrf_token() ?? "token" ?> : <?= csrf_token() ?>v,
            },
        },
        table   : "#tableOfMaquinastarifasimpresion",
        idSrc:  'id',
        fields: [ {
                name: "uso",
                type: "select",
                options: usoTypes
            }, {
                name: "tipo",
                type: "select",
                options: tipoTypes
            }, {
                name: "precio",
                attr: {
                    type: "text",
                    name : "precio",
                    class :"autonumeric"
        }
            }, {
                name: "margen",
                attr: {
                    type: "text",
                    name : "margen",
                    class :"autonumeric"
        }
            }, {
                "name": "maquina_id",
                "type": "hidden"
            },{
                "name": "deleted_at",
                "type": "hidden"
            },{
                "name": "is_deleted",
                "type": "hidden"
            },
        ]
    } );

    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: 6,
                unformatOnSubmit: true,
            });
        })
    })

    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]['maquina_id'] = id;
        }
        else if(type === 'edit' ) {
            for (v in d.data){
                d.data[v]['maquina_id'] = id;
            }
        }
    });
    
    
    editor.on( 'postSubmit', function ( e, json, data, action ) {
        
        updatePapeles()
    });


    editor2 = new $.fn.dataTable.Editor( {
        ajax: {
            url: "<?= route_to('editorOfMaquinasPapelImpresion') ?>", 
            headers: {
                <?= csrf_token() ?? "token" ?> : <?= csrf_token() ?>v,
            },
        },
        table   : "#tableOfPapelesImpresion",
        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"
            }
        ]
    } );

    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, 'sk-alert-2');
        }
    });

    
	var theTable = $('#tableOfMaquinastarifasimpresion').DataTable( {
		serverSide: true,
        processing: true,
        autoWidth: true,
        responsive: true,
        order: [[ 1, "asc" ]],
        pageLength: 5,
        lengthChange: false,
        searching: false, 
        paging: true, 
        info: false,
        dom: '<"mt-4"><"float-end"B><"float-start"l><t>', //"Blt",
		ajax : $.fn.dataTable.pipeline( {
            url: '<?= route_to('dataTableOfMaquinasTarifasImpresion') ?>',
            data: {
                id_maquina: id,
            },
            method: 'POST',
            headers: {'X-Requested-With': 'XMLHttpRequest'},
            async: true,
        }),
        columns: [
            { 'data': 'uso',  "render": function ( data, type, row, meta ) {
                    if(data=='interior')
                        return '<?= lang('MaquinasTarifasImpresions.interior') ?>';
                    else if (data=='cubierta')
                        return '<?= lang('MaquinasTarifasImpresions.cubierta') ?>';
                    else if (data=='sobrecubierta')
                        return '<?= lang('MaquinasTarifasImpresions.sobrecubierta') ?>';
                }
            },
            { 'data': 'tipo',  "render": function ( data, type, row, meta ) {
                    if(data=='negro')
                        return '<?= lang('MaquinasTarifasImpresions.negro') ?>';
                    else if (data=='negrohq')
                        return '<?= lang('MaquinasTarifasImpresions.negrohq') ?>';
                    else if (data=='bicolor')
                        return '<?= lang('MaquinasTarifasImpresions.bicolor') ?>';
                    else if (data=='color')
                        return '<?= lang('MaquinasTarifasImpresions.color') ?>';
                    else if (data=='colorhq')
                        return '<?= lang('MaquinasTarifasImpresions.colorhq') ?>';
                }
            },
            { 'data': 'precio',render : (d) => `<span class="autonumeric-decimal" data-decimal-places="6">${d}</span>` },
            { 'data': 'margen',render : (d) => `<span class="autonumeric">${d}</span>` },
            {
                data: actionBtns,
                className: 'row-edit dt-center'
            }
            
        ],
        columnDefs: [
            {
                target: 4,
                visible: true
            },
            {
                orderable: false,
                searchable: false,
                targets: [lastColNr]
            },
            {"orderData": [ 0, 1 ],    "targets": 0 },

        ],
        language: {
            url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json"
        },
        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>',
            }
        } ]
    } );

    
    var theTable2 = $('#tableOfPapelesImpresion').DataTable( {
		serverSide: true,
        processing: true,
        autoWidth: true,
        responsive: true,
        lengthMenu: [ 5, 10, 25, 50, 75, 100, 250],
        order: [[ 1, "asc" ]],
        pageLength: 25,
        lengthChange: true,
        searching: true, 
        paging: true, 
        info: true,
        stateSave: true,
        dom: "lftp",
		ajax : $.fn.dataTable.pipeline( {
            url: '<?= route_to('dataTableOfMaquinasPapelesImpresion') ?>',
            data: function (d) {
                d.maquina_id = id;
                d.isRotativa = $('#isRotativa').prop('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': 'papel_generico'},
            { 'data': 'papel_impresion'},
            { 'data': 'gramaje',render : (d) => `<span class="autonumeric">${d}</span>`},
            { 'data': 'bn'},
            { 'data': 'color'},
            { 'data': 'cubierta'},
            { 'data': 'sobrecubierta'},
            { 'data': 'rotativa'},
            { data: actionBtns2,
                    className: 'row-edit dt-center'}
        ],
        columnDefs: [
            {
                orderable: false,
                targets: [lastColNr2] 
            },
            {
                searchable: false,
                targets: [0,3,4,5,6,7,8,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"
        }
    } );

    
    // 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();
    } );
    
     
    // Activate an inline edit on click of a table cell
    $('#tableOfMaquinastarifasimpresion').on( 'click', 'tbody span.edit', function (e) {
        editor.inline(
            theTable.cells(this.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'
            } 
        );
    } );

    theTable2.on( 'draw.dt', function () {
        const boolCols = [4, 5, 6, 7, 8];
        for (let coln of boolCols) {
            theTable2.column(coln, { page: 'current' }).nodes().each( function (cell, i) {
                cell.innerHTML = cell.innerHTML == '1' ? '<i class="ti ti-check"></i>' : '';
            });
        }
    });
    
    // Delete row
    $(document).on('click', '.btn-delete', function(e) {
        $(".btn-remove").attr('data-id', $(this).attr('data-id'));
        const row = $(this).closest('tr')[0]._DT_RowIndex;
        
        if($(this).closest('table').attr('id').includes('tarifas')){
            $(".btn-remove").attr('table', "tarifas");
            $(".btn-remove").attr('row_index', row);
        }
        else if($(this).closest('table').attr('id').includes('Calles')){
            $(".btn-remove").attr('table', "calles");
            $(".btn-remove").attr('row_index', row);
        }
        else{
            $(".btn-remove").attr('table', );
        }
    });


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

            if($(this).attr('table').includes('tarifas')){
                remove_tarifas(dataId, row);
            }
            else if ($(this).attr('table').includes('calles')){
                remove_calles(dataId, row);
            }
        }
    });

    function remove_calles(dataId, row){
        $.ajax({
                url: `/maquinascalles/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)
        });
    };

    function remove_tarifas(dataId, row){

        $.ajax({
                url: `/maquinastarifasimpresion/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 calles -->
<!------------------------------------------->
<?= $this->section("additionalInlineJs") ?>

    var editor3 = new $.fn.dataTable.Editor( {
        ajax: {
            url: "<?= route_to('editorOfMaquinascalles') ?>", 
            headers: {
                <?= csrf_token() ?? "token" ?> : <?= csrf_token() ?>v,
            },
        },
        table   : "#tableOfCalles",
        idSrc:  'id',
        fields: [ {
                name: "formas"
            }, {
                name: "internas",
                attr: {
                    type: "text",
                    name : "internas",
                    class :"autonumeric"
                    }
            }, {
                name: "externas",
                attr: {
                    type: "text",
                    name : "externas",
                    class :"autonumeric"
            }
            }, {
                "name": "maquina_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: ".",
                allowDecimalPadding : 'floats',
                decimalPlaces: 2,
                unformatOnSubmit: true,
            });
        })
    })
        editor3.on('preSubmit', (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
                        }
                    });
                });
            }
        })

    editor3.on( 'preSubmit', function ( e, d, type ) {
        if ( type === 'create'){
            d.data[0]['maquina_id'] = id;
        }
        else if(type === 'edit' ) {
            for (v in d.data){
                d.data[v]['maquina_id'] = id;
            }
        }
    });
    
    
    editor3.on( 'postSubmit', function ( e, json, data, action ) {
        
        yeniden(json.<?= csrf_token() ?>);
    });


    editor3.on( 'submitSuccess', function ( e, json, data, action ) {
        
        theTable3.clearPipeline();
        theTable3.draw();
    });

    theTable3 = $('#tableOfCalles').DataTable({
        processing: true,
        serverSide: true,
        autoWidth: true,
        responsive: true,
        scrollX: true,
        lengthMenu: [ 5],
        pageLength: 10,
        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('dataTableOfMaquinascalles') ?>',
            data: {
                maquina_id: id,
            },
            method: 'POST',
            headers: {'X-Requested-With': 'XMLHttpRequest'},
            async: true,
        }),
        columns : [
            { 'data': 'formas' },
            { 'data': 'internas',render : (d) => `<span class="autonumeric">${d}</span>` },
            { 'data': 'externas',render : (d) => `<span class="autonumeric">${d}</span>` },
            { data: actionBtns,
                className: 'row-edit dt-center'}
        ],
        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
    $('#tableOfCalles').on( 'click', 'tbody span.edit', function (e) {
        editor3.inline(
            theTable3.cells(this.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'
            } 
        );
    } );

    

    

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



<?=$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 type="module" src="<?= site_url('assets/js/safekat/pages/maquinas/duplicate.js') ?>"></script>
    <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() ?>