<?= $this->include("themes/_commonPartialsBs/datatables") ?>
<?= $this->include("themes/_commonPartialsBs/select2bs5") ?>
<?= $this->include("themes/_commonPartialsBs/sweetalert") ?>
<?= $this->extend('themes/backend/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 ?>">
				<?= csrf_field() ?>
                <div class="card-body">
                    <?= view("themes/_commonPartialsBs/_alertBoxes") ?>
                    <?= !empty($validation->getErrors()) ? $validation->listErrors("bootstrap_style") : "" ?>
                    <?= view("themes/backend/vuexy/form/configuracion/maquinas/_maquinaFormItems") ?>
                </div><!-- /.card-body -->
                <div class="py-4">
                    <input type="submit"
                        class="btn btn-primary float-start me-sm-3 me-1"
                        name="save"
                        value="<?= lang("Basic.global.Save") ?>"
                    />
                    <?= anchor(route_to("maquinaList"), lang("Basic.global.Cancel"), ["class" => "btn btn-secondary float-start"]) ?>
                </div><!-- /.card-footer -->
			</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 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">
                    <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> <!-- //.accordion -->
<?php endif; ?>
    

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


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

    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);
    

    $(document).ready(function () {
        if($(this).is(':checked')){

            $("#datosRotativa").show();
        }
    });

    $('#isRotativa').on("click",function(el){
        
        Swal.fire({
            title: '<?= lang('MaquinasPapelImpresion.sureToChangeRotativaTitle') ?>',
            text: '<?= lang('MaquinasPapelImpresion.sureToChangeRotativaText') ?>',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            confirmButtonText: '<?= lang('Basic.global.yes') ?>',
            cancelButtonText: '<?= lang('Basic.global.Cancel') ?>',
            cancelButtonColor: '#d33'
        })
        .then((result) => {
            if (result.value) {
                
                if($(this).is(':checked')){
                    isRotativa.watch = 1;
                    $("#datosRotativa").show();
                }else{
                    document.getElementById("precioTintaNegro").value = null;
                    document.getElementById("precioTintaColor").value = null;
                    document.getElementById("velocidadCorte").value = null;
                    document.getElementById("precioHoraCorte").value = null;
                    document.getElementById("metrosxminuto").value = null;
                    $("#datosRotativa").hide();
                    isRotativa.watch = 0;
                }
                
                theTable2.clearPipeline();
                theTable2.draw();
                yeniden(response.<?= csrf_token() ?>);
            }
        });
    });

    $('#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('/');
    if(url_parts[url_parts.length-2] == 'edit'){
        id = url_parts[url_parts.length-1];
    }
    else{
        id = -1;
    }

    const actionBtns = function(data) {
        return `
                    <span class="edit"><i class="ti ti-pencil ti-sm btn-edit mx-2" data-id="${data.id}"></i></span>
                    <span class="cancel"></span>
                    <span class="remove"><i class="ti ti-trash ti-sm btn-delete mx-2" data-id="${data.id}"></i></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: "number"
                }
            }, {
                "name": "maquina_id",
                "type": "hidden"
            },{
                "name": "deleted_at",
                "type": "hidden"
            },{
                "name": "is_deleted",
                "type": "hidden"
            },
        ]
    } );


    editor.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;
            }
        }
    });
    
    
    editor.on( 'postSubmit', function ( e, json, data, action ) {
        
        yeniden(json.<?= csrf_token() ?>);

        $.ajax({
            url: '<?= route_to('updateMaquinaPapelOnTarifasChange') ?>',
            data: {
                maquina_id: id,
                isRotativa: isRotativa.watch,
                <?= 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();
            }
        });
    });


    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;
            Swal.fire({
                icon: 'error',
                title: '<?= lang('Basic.global.sweet.error_tittle') ?>',
                text: json.error,
            });
        }
    });

    
	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' },
            {
                data: actionBtns,
                className: 'row-edit dt-center'
            }
            
        ],
        columnDefs: [
            {
                orderable: false,
                searchable: false,
                targets: [lastColNr]
            },
            {"orderData": [ 0, 1 ],    "targets": 0 },

        ],
        language: {
            url: "//cdn.datatables.net/plug-ins/1.13.4/i18n/<?= config('Basics')->i18n ?>.json"
        },
        buttons: [ {
            className: 'btn btn-primary float-end me-sm-3 me-1',
            extend: "createInline",
            editor: editor,
            formOptions: {
                submitTrigger: -1,
                submitHtml: '<i class="ti ti-device-floppy"/>'
            }
        } ]
    } );

    
    var theTable2 = $('#tableOfPapelesImpresion').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('dataTableOfMaquinasPapelesImpresion') ?>',
            data: function (d) {
                d.maquina_id = id;
                d.isRotativa = isRotativa.watch;
                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'},
            { 'data': 'bn'},
            { 'data': 'color'},
            { 'data': 'cubierta'},
            { 'data': 'sobrecubierta'},
            { 'data': 'rotativa'},
            { 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: "//cdn.datatables.net/plug-ins/1.13.4/i18n/<?= config('Basics')->i18n ?>.json"
        },
        columnDefs: [
            {
                searchable: false,
                targets: [0,3,4,5,6,7,8]
            }
        ],
    } );

    
    // 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: '<i class="ti ti-x"></i>',
                cancelTrigger: 'span.cancel',
                submitHtml: '<i class="ti ti-device-floppy"></i>',
                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
    $('#tableOfMaquinastarifasimpresion').on( 'click', 'tbody span.remove', function (e) {
        
        Swal.fire({
            title: '<?= lang('Basic.global.sweet.sureToDeleteTitle', [mb_strtolower(lang('Basic.global.sweet.line'))]) ?>',
            text: '<?= lang('Basic.global.sweet.sureToDeleteText') ?>',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            confirmButtonText: '<?= lang('Basic.global.sweet.deleteConfirmationButton') ?>',
            cancelButtonText: '<?= lang('Basic.global.Cancel') ?>',
            cancelButtonColor: '#d33'
        })
        .then((result) => {
            const dataId = $(this).data('id');
            const row = $(this).closest('tr');
            if (result.value) {
                editor
                    .create( false )
                    .edit( this.parentNode, false)
                    .set( 'deleted_at', new Date().toISOString().slice(0, 19).replace('T', ' ') )
                    .set( 'is_deleted', 1 )
                    .submit();
            }
        });
    });

    
    

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

<?=$this->section('css') ?>
    <link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.2.3/css/buttons.bootstrap5.min.css">

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


<?= $this->section('additionalExternalJs') ?>
    <script src="https://cdn.datatables.net/buttons/2.2.3/js/dataTables.buttons.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.2.3/js/buttons.<?=config('Basics')->theme['name'] == 'Bootstrap5' ? 'bootstrap5' : 'bootstrap4' ?>.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.2.3/js/buttons.html5.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.2.3/js/buttons.print.min.js"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.0/jszip.min.js" integrity="sha512-xcHCGC5tQ0SHlRX8Anbz6oy/OullASJkEhb4gjkneVpGE3/QGYejf14CUO5n5q5paiHfRFTa9HKgByxzidw2Bw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.5/pdfmake.min.js" integrity="sha512-rDbVu5s98lzXZsmJoMa0DjHNE+RwPJACogUCLyq3Xxm2kJO6qsQwjbE5NDk2DqmlKcxDirCnU1wAzVLe12IM3w==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.5/vfs_fonts.js" integrity="sha512-cktKDgjEiIkPVHYbn8bh/FEyYxmt4JDJJjOCu5/FQAkW4bc911XtKYValiyzBiJigjVEvrIAyQFEbRJZyDA1wQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

    <script src="<?= site_url('themes/vuexy/js/datatables-editor/dataTables.editor.js') ?>"></script>

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