<?= $this->include('themes/_commonPartialsBs/datatables') ?>
<?= $this->include("themes/_commonPartialsBs/select2bs5") ?>
<?= $this->include("themes/_commonPartialsBs/sweetalert") ?>
<?= $this->include('themes/_commonPartialsBs/_confirm2delete') ?>
<?=$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="tarifaAcabadoForm" class="card-body" method="post" action="<?= $formAction ?>">
				<?= csrf_field() ?>
                <?= view("themes/_commonPartialsBs/_alertBoxes") ?>
                <?= !empty($validation->getErrors()) ? $validation->listErrors("bootstrap_style") : "" ?>
                <?= view("themes/backend/vuexy/form/tarifas/acabado/_tarifaAcabadoFormItems") ?>
				<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") ?>"
					/>
					<?= anchor(route_to("tarifaAcabadoList"), lang("Basic.global.Cancel"), ["class" => "btn btn-secondary float-start"]) ?>
				</div><!-- /.card-footer -->
			</form>
		</div><!-- //.card -->
    </div><!--//.col -->

    <?php if($formAction == route_to('createTarifaAcabado')): ?>
        <div class="accordion mt-3" id="accordionAcabadoLineas" style="visibility:hidden" >
    <?php else: ?>
        <div class="accordion mt-3" id="accordionAcabadoLineas" style="visibility:visible" >
    <?php endif; ?>
            <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("TarifaAcabadoLineas.moduleTitle") ?></h3>
                    </button>
                </h2>

                <div id="accordionTip1" class="accordion-collapse collapse show" data-bs-parent="#accordionAcabadoLineas">
                    <div class="accordion-body">
                        <table id="tableOfTarifaacabadolineas" class="table table-striped table-hover" style="width: 100%;">
                            <thead>
                                <tr>
                                    <th><?= lang('TarifaAcabadoLineas.tiradaMin') ?></th>
                                    <th><?= lang('TarifaAcabadoLineas.precioMax') ?></th>
                                    <th><?= lang('TarifaAcabadoLineas.tiradaMax') ?></th>
                                    <th><?= lang('TarifaAcabadoLineas.precioMin') ?></th>
                                    <th><?= lang('TarifaAcabadoLineas.margen') ?></th>
                                    <th style="min-width:100px"></th>
                                </tr>
                            </thead>
                            <tbody>
                            </tbody>
                        </table>   
                    </div>
                </div>
            </div>
        </div> <!-- //.accordion -->
    

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

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


<?= $this->section("additionalInlineJs") ?>
    const lastColNr = $('#tableOfTarifasacabado').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"><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>
            `;
    };


	editor = new $.fn.dataTable.Editor( {
        ajax: {
            url: "<?= route_to('editorOfTarifaAcabadoLineas') ?>", 
            headers: {
                <?= csrf_token() ?? "token" ?> : <?= csrf_token() ?>v,
            },
        },
        table   : "#tableOfTarifaacabadolineas",
        idSrc:  'id',
        fields: [ {
                name: "tirada_min"
            }, {
                name: "precio_max"
            }, {
                name: "tirada_max"
            }, {
                name: "precio_min"
            },{
                name: "margen"
            }, {
                "name": "tarifa_acabado_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]['tarifa_acabado_id'] = id;
        }
        else if(type === 'edit' ) {
            for (v in d.data){
                d.data[v]['tarifa_acabado_id'] = id;
            }
        }
    });
    
    
    editor.on( 'postSubmit', function ( e, json, data, action ) {
        
        yeniden(json.<?= csrf_token() ?>);
    });

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


	var theTable = $('#tableOfTarifaacabadolineas').DataTable( {
		serverSide: true,
        processing: true,
        autoWidth: true,
        responsive: true,
        lengthMenu: [ 5, 10, 25],
        order: [[ 0, "asc" ], [ 1, "asc" ]],
        pageLength: 10,
        lengthChange: true,
        searching: false, 
        paging: true, 
        info: false,
        dom: '<"mt-4"><"float-end"B><"float-start"l><t><"mt-4 mb-3"p>',
		ajax : $.fn.dataTable.pipeline( {
            url: '<?= route_to('dataTableOfTarifaAcabadoLineas') ?>',
            data: {
                id_tarifaacabado: id,
            },
            method: 'POST',
            headers: {'X-Requested-With': 'XMLHttpRequest'},
            async: true,
        }),
        columns: [
            { 'data': 'tirada_min' },
            { 'data': 'precio_max' },
            { 'data': 'tirada_max' },
            { 'data': 'precio_min' },
            { 'data': 'margen' },
            {
                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 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>'
            }
        } ]
    } );

    
    
    // Activate an inline edit on click of a table cell
    $('#tableOfTarifaacabadolineas').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'
            } 
        );
    } );

    
    // Delete row
    $(document).on('click', '.btn-delete', function(e) {
        $(".btn-remove").attr('data-id', $(this).attr('data-id'));
    });

    $(document).on('click', '.btn-remove', function(e) {
        const dataId = $(this).attr('data-id');
        const row = $(this).closest('tr');
        if ($.isNumeric(dataId)) {
            $.ajax({
                url: `/tarifas/tarifaacabadolineas/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() ?>

<?=$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.bootstrap5.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.min.js') ?>"></script>
<?=$this->endSection() ?>

