<?= $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="tarifaEnvioForm" 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/tarifas/envios/_tarifaEnvioFormItems") ?>
			</div><!-- /.card-body -->
			<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("tarifaEnvioList"), lang("Basic.global.Cancel"), ["class" => "btn btn-secondary float-start",]) ?> 	
			</div><!-- /.card-footer -->
            
			</form>
    </div><!-- //.card -->
    </div><!--//.col -->

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

                <div id="accordionTip1" class="accordion-collapse collapse show" data-bs-parent="#accordionZonas">
                    <div class="accordion-body">
                        
                        <table id="tableOfZonas" class="table table-striped table-hover" style="width: 100%;">
                            <thead>
                                <tr>
                                    <th><?= lang('TarifasEnviosZonas.cpInicial') ?></th>
                                    <th><?= lang('TarifasEnviosZonas.cpFinal') ?></th>
                                    <th><?= lang('TarifasEnviosZonas.importeFijo') ?></th>
                                    <th></th>
                                </tr>
                            </thead>
                            <tbody>
                            </tbody>
                        </table>   
                    </div>
                </div>
            </div>
	    </div> <!-- //.accordion -->


        <div class="accordion mt-3" id="accordionPrecios" style="visibility:visible" >
            <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("TarifasEnviosPrecios.moduleTitle") ?></h3>
                    </button>
                    
                </h2>

                <div id="accordionTip2" class="accordion-collapse collapse show" data-bs-parent="#accordionPrecios">
                    <div class="accordion-body">
                        
                        <table id="tableOfPrecios" class="table table-striped table-hover" style="width: 100%;">
                            <thead>
                                <tr>
                                    <th><?= lang('TarifasEnviosPrecios.proveedorId') ?></th>
                                    <th><?= lang('TarifasEnviosPrecios.tipoEnvio') ?></th>
                                    <th><?= lang('TarifasEnviosPrecios.pesoMin') ?></th>
                                    <th><?= lang('TarifasEnviosPrecios.pesoMax') ?></th>
                                    <th><?= lang('TarifasEnviosPrecios.precio') ?></th>
                                    <th><?= lang('TarifasEnviosPrecios.precioAdicional') ?></th>
                                    <th></th>
                                </tr>
                            </thead>
                            <tbody>
                            </tbody>
                        </table>   
                    </div>
                </div>
            </div>
	    </div> <!-- //.accordion -->
	<?php endif; ?>

</div><!--//.row -->
<?= $this->endSection() ?>



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


<!------------------------------------------->
<!-- Código JS para  general -->
<!------------------------------------------->
<?= $this->section("additionalInlineJs") ?>
    const url = window.location.href;
    const url_parts = url.split('/');
    var id = -1;
    if(url_parts[url_parts.length-2] == 'edit'){
        id = url_parts[url_parts.length-1];
    }
    else{
        id = -1;
    }

    <?php if(str_contains($formAction, 'edit')): ?>
    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>
            `;
    };

    // 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('zonas')){
            $(".btn-remove").attr('table', "zonas");
        }
        else if($(this).closest('table').attr('id').includes('precios')){
            $(".btn-remove").attr('table', "precios");
        }
        else{
            $(".btn-remove").attr('table', );
        }
    });

    var selected_zona_id = -1;

   
    $(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('zonas')){
                remove_zonas(dataId, row);
            }
            else if ($(this).attr('table').includes('precios')){
                remove_precios(dataId, row);
            }
        }
    });
    <?php endif; ?>
<?= $this->endSection() ?>


<!------------------------------------------->
<!-- Código JS para  tableOfZonas -->
<!------------------------------------------->
<?= $this->section("additionalInlineJs") ?>
	const lastColNr = $('#tableOfZonas').find("tr:first th").length - 1;

	var editor = new $.fn.dataTable.Editor( {
        ajax: {
            url: "<?= route_to('editorOfTarifasEnvioZonas') ?>", 
            headers: {
                <?= csrf_token() ?? "token" ?> : <?= csrf_token() ?>v,
            },
        },
        table   : "#tableOfZonas",
        idSrc:  'id',
        fields: [ {
                name: "cp_inicial"
            }, {
                name: "cp_final"
            }, {
                name: "importe_fijo"
            }, {
                "name": "tarifa_envio_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_envio_id'] = id;
        }
        else if(type === 'edit' ) {
            for (v in d.data){
                d.data[v]['tarifa_envio_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 = $('#tableOfZonas').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,
		select: 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('dataTableOfTarifasEnvioZonas') ?>',
            data: function ( d ) {
                d.tarifa_envio_id =  id;
            },
            method: 'POST',
            headers: {'X-Requested-With': 'XMLHttpRequest'},
            async: true,
        }),
        columns: [
            { 'data': 'cp_inicial' },
            { 'data': 'cp_final' },
            { 'data': 'importe_fijo' },
            {
                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: '<a href="javascript:void(0);"><i class="ti ti-device-floppy"></i></a>'
            
            }
        } ]
    } );

    
    // Activate an inline edit on click of a table cell
    $('#tableOfZonas').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
    function remove_zonas(dataId, row){

        $.ajax({
                url: `/tarifas/tarifasenvioszonas/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)
        });
    }      
	

	theTable.on( 'select', function ( e, dt, type, indexes ) {
        if ( type === 'row' ) {
            selected_zona_id = parseInt(theTable.rows( indexes ).data().pluck( 'id' )[0]);
            theTable2.clearPipeline();
            theTable2.draw();
        }
    } );

    theTable.on( 'deselect', function ( e, dt, type, indexes ) {
        if ( theTable.rows( '.selected' ).count() == 0 ) {
            selected_zona_id = -1;
            theTable2.clearPipeline();
            theTable2.draw();
        }
    } );
<?= $this->endSection() ?>


<!------------------------------------------->
<!-- Código JS para  tableOfPrecios -->
<!------------------------------------------->
<?= $this->section("additionalInlineJs") ?>
const lastColNr2 = $('#tableOfPrecios').find("tr:first th").length - 1;

	var editor2 = new $.fn.dataTable.Editor( {
        ajax: {
            url: "<?= route_to('editorOfTarifasEnvioPrecios') ?>", 
            headers: {
                <?= csrf_token() ?? "token" ?> : <?= csrf_token() ?>v,
            },
        },
        table   : "#tableOfPrecios",
        idSrc:  'id',
        fields: [ 
            {
                "name": "proveedor_id",
                "type": "select"
            }, {
                name: "tipo_envio"
            }, {
                name: "peso_min"
            }, {
                name: "peso_max"
            }, {
                name: "precio"
            }, {
                name: "precio_adicional"
            }, {
                "name": "zona_envio_id",
                "type": "hidden"
            }, {
                "name": "proveedor_id",
                "type": "hidden"
            }, {
                "name": "deleted_at",
                "type": "hidden"
            },{
                "name": "is_deleted",
                "type": "hidden"
            },
        ]
    } );

    // Generación de la lista de proveedores (id, nombre) para encuadernación
    const suppliersList = <?php echo json_encode($proveedores); ?>;
    editor2.field( 'proveedor_id' ).update( suppliersList );

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


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


    var theTable2 = $('#tableOfPrecios').DataTable( {
		serverSide: true,
        processing: true,
        autoWidth: true,
        responsive: true,
        lengthMenu: [ 5, 10, 25, 50, 100],
        order: [[ 0, "asc" ], [ 1, "asc" ]],
        pageLength: 25,
        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('dataTableOfTarifasEnvioPrecios') ?>',
            data: function ( d ) {
                d.zona_envio_id =  selected_zona_id;
            },
            method: 'POST',
            headers: {'X-Requested-With': 'XMLHttpRequest'},
            async: true,
        }),
        columns: [
            { 'data': 'proveedor' },
            { 'data': 'tipo_envio' },
            { 'data': 'peso_min' },
            { 'data': 'peso_max' },
            { 'data': 'precio' },
            { 'data': 'precio_adicional' },
            {
                data: actionBtns,
                className: 'row-edit dt-center'
            }
        ],
        columnDefs: [
            {
                orderable: false,
                searchable: false,
                targets: [lastColNr2]
            },
            {"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: editor2,
            formOptions: {
                submitTrigger: -1,
                submitHtml: '<a href="javascript:void(0);"><i class="ti ti-device-floppy"></i></a>'
            
            },
            action: function ( e, dt, node, config ) {
                if(selected_zona_id == -1){
                    popErrorAlert("<?= lang('TarifasEnviosPrecios.validation.error_seleccion_zonas') ?>");
                }
                else{
                    formOptions= {
                        submitTrigger: -1,
                        submitHtml: '<a href="javascript:void(0);"><i class="ti ti-device-floppy"></i></a>'
                    
                    };
                    editor2.inlineCreate(config.position, formOptions);      
                }
            },
        } ],

    } );

    
    // Activate an inline edit on click of a table cell
    $('#tableOfPrecios').on( 'click', 'tbody span.edit', function (e) {
        editor.inline(
            theTable2.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
    function remove_precios(dataId, row){

        $.ajax({
                url: `/tarifas/tarifasenviosprecios/delete/${dataId}`,
                method: 'GET',
            }).done((data, textStatus, jqXHR) => {
                $('#confirm2delete').modal('toggle');
                theTable2.clearPipeline();
                theTable2.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="<?= site_url('themes/vuexy/css/datatables-editor/editor.dataTables.min.css') ?>">
    <link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.2.3/css/buttons.bootstrap5.min.css">
    <link rel="stylesheet" href="<?= site_url('themes/vuexy/css/sk-datatables.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/select/1.7.0/js/dataTables.select.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() ?>


<?php endif; ?>

